Напиши скрипт на Python или языке, который лучше подходит для этого, программу, которая…
- User
Напиши скрипт на Python или языке, который лучше подходит для этого, программу, которая собирает в одном маркдаун-файле изменения между переводами игры.
Есть 16 версий игры, переводы которых я хочу сравнить.
Первые 5 версий игры используют формат именования файлов en_US.lang и ru_RU.lang. Первые 8 строк из перевода 1 версии вылядят следующим образом:
language.name=English language.region=US language.code=en_US gui.done=Done gui.cancel=Cancel gui.back=BackСледующие 2 версии игры используют формат именования файлов en_us.lang и ru_ru.lang. Первые 8 строк из перевода 6 версии вылядят следующим образом:
language.name=English language.region=United States language.code=en_us gui.done=Done gui.cancel=Cancel gui.back=BackСледующие 9 версий игры используют формат именования файлов en_us.json и ru_ru.json. Первые 8 строк из перевода 8 версии вылядят следующим образом:
{ "language.name": "English", "language.region": "United States", "language.code": "en_us", "gui.done": "Done", "gui.cancel": "Cancel", "gui.back": "Back", "gui.toTitle": "Back to title screen",Программа принимает на вход путь к каталогу, в котором находится 16 каталогов, представляющих каждую из версий игры. В каждом из каталогов версии игры по 2 файла: английский язык игры и русский язык.
Программа должна определять формат и извлекать данные соответствующим образом.
В результате программа должна создать файл output.md в каталоге своего местонахождения.
Примерное содержание output.md:
# Все строки перевода игры и различия между ними в разных версиях ## {ключ строки перевода} (появился в версии {название папки версии}) | Версия | На английском | На русском | | --- | --- | --- | | {название папки версии} | {строка перевода из файла английского языка} | {строка перевода из файла русского языка} | ## {ключ строки перевода} (появился в версии {название папки версии}) | Версия | На английском | На русском | | --- | --- | --- | | {название папки версии} | {строка перевода из файла английского языка} | {строка перевода из файла русского языка} | - Assistant
Here's a Python script that accomplishes your requirements. It reads the translation files from each version directory, handles the different file formats (
.langand.json), and generates anoutput.mdfile with all the translation keys, the versions in which they appear, and the English and Russian translations.import os import json import sys def parse_translation_file(filepath): ext = os.path.splitext(filepath)[1].lower() if ext == '.lang': translations = {} with open(filepath, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line or line.startswith('#') or line.startswith('//'): continue if '=' in line: key, value = line.split('=', 1) translations[key.strip()] = value.strip() return translations elif ext == '.json': with open(filepath, 'r', encoding='utf-8') as f: translations = json.load(f) return translations else: raise ValueError('Unknown file type for file: ' + filepath) def escape_markdown(text): markdown_special_chars = '\\`*_{}[]()<>#+-.!|' for char in markdown_special_chars: text = text.replace(char, '\\' + char) return text def main(): if len(sys.argv) != 2: print("Usage: script.py <path_to_versions_directory>") sys.exit(1) base_dir = sys.argv[1] output_filename = 'output.md' version_dirs = sorted([d for d in os.listdir(base_dir) if os.path.isdir(os.path.join(base_dir, d))]) translations = {} for version_dir in version_dirs: version_path = os.path.join(base_dir, version_dir) files_in_version = os.listdir(version_path) en_file = None ru_file = None for filename in files_in_version: if filename.lower().startswith('en_') and (filename.lower().endswith('.lang') or filename.lower().endswith('.json')): en_file = filename elif filename.lower().startswith('ru_') and (filename.lower().endswith('.lang') or filename.lower().endswith('.json')): ru_file = filename if not en_file or not ru_file: print(f"Could not find both English and Russian translation files in version directory {version_dir}") continue en_filepath = os.path.join(version_path, en_file) ru_filepath = os.path.join(version_path, ru_file) try: en_translations = parse_translation_file(en_filepath) ru_translations = parse_translation_file(ru_filepath) except Exception as e: print(f"Error parsing files in version {version_dir}: {e}") continue for key in set(en_translations.keys()).union(ru_translations.keys()): en_value = en_translations.get(key, '') ru_value = ru_translations.get(key, '') if key not in translations: translations[key] = { 'first_version': version_dir, 'versions': { version_dir: {'en': en_value, 'ru': ru_value} } } else: translations[key]['versions'][version_dir] = {'en': en_value, 'ru': ru_value} with open(output_filename, 'w', encoding='utf-8') as out_file: out_file.write('# Все строки перевода игры и различия между ними в разных версиях\n\n') for key in sorted(translations.keys()): first_version = translations[key]['first_version'] out_file.write(f'## {key} (появился в версии {first_version})\n\n') out_file.write('| Версия | На английском | На русском |\n') out_file.write('| --- | --- | --- |\n') versions_with_key = translations[key]['versions'] for version in version_dirs: if version in versions_with_key: en_value = escape_markdown(versions_with_key[version]['en']) ru_value = escape_markdown(versions_with_key[version]['ru']) out_file.write(f'| {version} | {en_value} | {ru_value} |\n') out_file.write('\n') if __name__ == '__main__': main()Usage:
-
Save the script as
script.py. -
Run the script from the command line, providing the path to the directory containing the version folders:
python script.py /path/to/versions_directoryReplace
/path/to/versions_directorywith the actual path to your directory containing the 16 version subdirectories.
Explanation:
- The script starts by defining a function
parse_translation_filethat reads a translation file and returns a dictionary of key-value pairs. It handles both.langand.jsonfile formats. - The
escape_markdownfunction ensures that any special Markdown characters in the translation strings are properly escaped, so they don't interfere with the Markdown formatting. - The
mainfunction processes each version directory:- It identifies the English and Russian translation files based on their filenames.
- It parses the translation files to extract the translations.
- It builds a data structure that keeps track of all translation keys, the first version in which they appear, and their translations in each version.
- Finally, the script writes the
output.mdfile, formatting the data as specified.
Notes:
- Ensure that your version directories are named in a way that when sorted, they are in chronological order (e.g.,
version1,version2, ...,version16). This ensures that the script correctly identifies the first version in which a key appears. - The script assumes that each version directory contains exactly two translation files: one for English and one for Russian, following the naming patterns you've described.
- If there are any keys present in one language file but not the other, the script handles them by using an empty string for the missing translation.
- If there are any issues parsing the files, the script will output an error message and skip that version.
Example
output.md:# Все строки перевода игры и различия между ними в разных версиях ## language.name (появился в версии version1) | Версия | На английском | На русском | | --- | --- | --- | | version1 | English | Английский | | version2 | English | Английский | | ... | ... | ... | ## language.region (появился в версии version1) | Версия | На английском | На русском | | --- | --- | --- | | version1 | United States | Соединённые Штаты | | version2 | United Kingdom | Великобритания | | ... | ... | ... | ## gui.done (появился в версии version1) | Версия | На английском | На русском | | --- | --- | --- | | version1 | Done | Готово | | version2 | Done | Готово | | ... | ... | ... |(Note: The above is an illustrative example. Your actual
output.mdwill reflect the actual translations and versions in your files.)Dependencies:
- The script uses standard Python libraries:
os,json, andsys. No additional packages are required.
Handling Special Characters:
- The
escape_markdownfunction takes care of escaping characters that have special meaning in Markdown, such as|,*,_, etc.
Error Handling:
- If the script cannot find both the English and Russian translation files in a version directory, it will output a message and skip that version.
- If there is an error parsing the translation files, it will output an error message and continue processing the next version.
Let me know if you need further assistance or modifications to this script.
-