MCPcopy Create free account
hub / github.com/comaps/comaps / CategoriesTxt

Class CategoriesTxt

tools/python/categories_converter.py:56–124  ·  view source on GitHub ↗

For now, let's allow comments only at the beginning of the file.

Source from the content-addressed store, hash-verified

54
55
56class CategoriesTxt:
57 """For now, let's allow comments only at the beginning of the file."""
58 def __init__(self, filepath):
59 self.translations = defaultdict(lambda: defaultdict(str))
60 self.keys_in_order = []
61 self.comments = []
62 self.filepath = filepath
63 self.all_langs = set()
64 self.parse_file()
65
66
67 def parse_file(self):
68 current_key = ""
69 this_line_is_key = True
70 with open(self.filepath) as infile:
71 for line in map(str.strip, infile):
72 if line.startswith("#"):
73 self.comments.append(line)
74 this_line_is_key = True
75 elif not line:
76 this_line_is_key = True
77 elif this_line_is_key:
78 self.keys_in_order.append(line)
79 current_key = line
80 this_line_is_key = False
81 else:
82 pos = line.index(':')
83 lang = line[:pos]
84 translation = line[pos + 1:]
85 self.translations[current_key][lang] = translation
86
87
88 def write_as_categories(self, outfile):
89 self.write_strings_formatted(outfile, "\n{}\n", "{}:{}\n")
90
91
92 def write_as_strings(self, filepath):
93 with open(filepath, "w") as outfile:
94 self.write_strings_formatted(outfile, key_format="\n [{}]\n", line_format=" {} = {}\n")
95
96
97 def write_strings_formatted(self, outfile, key_format, line_format):
98 for key in self.keys_in_order:
99 outfile.write(key_format.format(key.strip("[]")))
100 pair = self.translations[key]
101 for lang in ITUNES_LANGS:
102 if lang in pair:
103 outfile.write(line_format.format(lang, pair[lang]))
104 remaining_langs = sorted(list(set(pair.keys()) - set(ITUNES_LANGS)))
105 for lang in remaining_langs:
106 outfile.write(line_format.format(lang, pair[lang]))
107
108
109 def add_translation(self, translation, key, lang):
110 if key not in self.keys_in_order:
111 self.keys_in_order.append(key)
112 self.translations[key][lang] = translation
113

Callers 2

__init__Method · 0.90
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected