generate-country-names.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env python
  2. # Usage: ./generate-country-names.py /path/to/openjdk-src/
  3. # It should have make/data/cldr/common/main/*.xml for country names generation
  4. import xml.dom.minidom
  5. import sys
  6. import os
  7. country_translations = {}
  8. def traverse(file, node, lang):
  9. for e in node.childNodes:
  10. if e.localName == None:
  11. continue
  12. if e.nodeName == "territory" and e.hasAttribute("type"):
  13. country = e.getAttribute("type")
  14. # Skip invalid country
  15. if not (country[0] >= "A" and country[0] <= "Z") \
  16. or country == "EZ" or country == "UN" or country == "XA" or country == "XB" or country == "ZZ":
  17. continue
  18. translation = ""
  19. if country == "HK" or country == "MO" or country == "PS":
  20. if e.hasAttribute("alt"):
  21. translation = e.firstChild.nodeValue
  22. elif not e.hasAttribute("alt"):
  23. translation = e.firstChild.nodeValue
  24. if translation == "":
  25. continue
  26. # Make sure no tab in translation
  27. translation = translation.replace("\t", " ")
  28. if not country in country_translations:
  29. country_translations[country] = {}
  30. country_translations[country][lang] = translation
  31. traverse(file, e, lang)
  32. lang_list = []
  33. for file in os.listdir("../data/po"):
  34. if file.endswith(".po"):
  35. lang_list.append(os.path.splitext(file)[0].replace("_", "-"))
  36. lang_list.sort()
  37. real_lang_list = []
  38. for lang in lang_list:
  39. # Avoid fallback language except tranditional chinese
  40. target_name = lang.split("-")[0]
  41. if lang == "zh-TW":
  42. target_name = "zh_Hant"
  43. jdk_source = ' '.join(sys.argv[1:])
  44. target_file = jdk_source + "/make/data/cldr/common/main/" + target_name + ".xml"
  45. # Use english if no such translation
  46. if not os.path.isfile(target_file):
  47. continue
  48. try:
  49. doc = xml.dom.minidom.parse(target_file)
  50. except Exception as ex:
  51. print("============================================")
  52. print("/!\\ Expat doesn't like ", file, "! Error=", type(ex), " (", ex.args, ")")
  53. print("============================================")
  54. traverse(file, doc, lang)
  55. real_lang_list.append(lang)
  56. f = open('../data/country_names.tsv', 'w')
  57. f.write("country_code")
  58. for language in real_lang_list:
  59. f.write("\t")
  60. f.write(language)
  61. f.write("\n")
  62. for country in country_translations.keys():
  63. f.write(country)
  64. for language in real_lang_list:
  65. f.write("\t")
  66. if language in country_translations[country].keys():
  67. f.write(country_translations[country][language])
  68. else:
  69. f.write(country_translations[country]["en"])
  70. f.write("\n")