| 1 |
def merge_po_files_preserve_format(base_file, new_file, output_file): |
| 2 |
with open(base_file, 'r', encoding='utf-8') as f1, open(new_file, 'r', encoding='utf-8') as f2: |
| 3 |
base_lines = f1.readlines() |
| 4 |
new_lines = f2.readlines() |
| 5 |
|
| 6 |
# Traverse the new_lines and extract msgid and msgstr |
| 7 |
new_translations = {} |
| 8 |
i = 0 |
| 9 |
while i < len(new_lines): |
| 10 |
if new_lines[i].startswith('msgid '): |
| 11 |
msgid_start = i |
| 12 |
while not new_lines[i].startswith('msgstr '): |
| 13 |
i += 1 |
| 14 |
msgid = ''.join(new_lines[msgid_start:i]) |
| 15 |
msgstr = new_lines[i].split('msgstr ')[1].strip() |
| 16 |
new_translations[msgid] = msgstr |
| 17 |
i += 1 |
| 18 |
|
| 19 |
# Open the output_file and write the merged content |
| 20 |
with open(output_file, 'w', encoding='utf-8') as output: |
| 21 |
i = 0 |
| 22 |
while i < len(base_lines): |
| 23 |
if base_lines[i].startswith('msgid '): |
| 24 |
msgid_start = i |
| 25 |
while not base_lines[i].startswith('msgstr '): |
| 26 |
i += 1 |
| 27 |
msgid = ''.join(base_lines[msgid_start:i]) |
| 28 |
if msgid in new_translations: |
| 29 |
output.write(f'{msgid}') |
| 30 |
output.write(f'msgstr {new_translations[msgid]}\n') |
| 31 |
else: |
| 32 |
output.write(base_lines[i]) |
| 33 |
i += 1 |
| 34 |
else: |
| 35 |
output.write(base_lines[i]) |
| 36 |
i += 1 |
| 37 |
|
| 38 |
if __name__ == '__main__': |
| 39 |
base_file = 'base.po' |
| 40 |
new_file = 'new.po' |
| 41 |
output_file = 'output.po' |
| 42 |
merge_po_files_preserve_format(base_file, new_file, output_file) |