Lex2Po/Po2Lex.py

57 lines
2.0 KiB
Python
Raw Normal View History

2024-07-18 17:28:22 +02:00
import re
2024-07-19 11:27:11 +02:00
import os
2024-07-18 17:28:22 +02:00
from pathlib import Path
# Function to read and process .po file
def process_po_file(file_name):
2024-07-19 11:27:11 +02:00
try:
with open(file_name, "r") as file:
content = file.read()
2024-07-18 17:28:22 +02:00
2024-07-19 11:27:11 +02:00
entries = re.findall(r"(msgctxt\s+\".+?\"\nmsgid\s+\".+?\"\nmsgstr\s+\".+?\")", content, re.DOTALL)
2024-07-18 17:28:22 +02:00
2024-07-19 11:27:11 +02:00
result = []
for entry in entries:
lines = entry.split("\n")
msgctxt_line = lines[0]
msgid_lines = [line for line in lines if line.startswith("msgid")]
msgstr_lines = [line for line in lines if line.startswith("msgstr")]
2024-07-18 17:28:22 +02:00
2024-07-19 11:27:11 +02:00
msgctxt = re.findall(r"msgctxt\s+\"(.+?)\"", msgctxt_line)[0]
msgid = " ".join(re.findall(r"msgid\s+\"(.+?)\"", "\n".join(msgid_lines)))
msgstr = " ".join(re.findall(r"msgstr\s+\"(.+?)\"", "\n".join(msgstr_lines)))
2024-07-18 17:28:22 +02:00
2024-07-19 11:27:11 +02:00
result.append({"msgctxt": msgctxt, "msgid": msgid, "msgstr": msgstr})
2024-07-18 17:28:22 +02:00
2024-07-19 11:27:11 +02:00
return result
except Exception as e:
print(f"Process_po_file Exception {e} in {file_name} {msgctxt_line}")
quit()
2024-07-18 17:28:22 +02:00
# Function to create .lex file
def create_lex_file(translations, lex_file_name):
with open(lex_file_name, "w") as file:
for translation in translations:
file.write(f"'{translation['msgctxt']}' => '{translation['msgstr']}',\n")
# Main program
2024-07-19 11:27:11 +02:00
SOURCE_BASE_DIR = Path("/home/brianr/Documents/smeserver-manager-locale/root/usr/share/smanager/lib/SrvMngr/I18N/Modules")
# Iterate over subdirectories in SOURCE_BASE_DIR
for subdir in [subdir.path for subdir in os.scandir(SOURCE_BASE_DIR) if subdir.is_dir()]:
module_name = Path(subdir).name
print(f"Processing {module_name}")
po_dir = Path(os.path.join(subdir, "pofiles"))
#print(po_dir)
lex_dir = Path(os.path.join(subdir, "newlex"))
#print(lex_dir)
# Ensure the newlex directory exists
lex_dir.mkdir(parents=True, exist_ok=True)
for file in os.listdir(po_dir):
if file.endswith(".po"):
po_file_path = Path(os.path.join(po_dir, file))
translations = process_po_file(po_file_path)
lex_file_name = lex_dir / (po_file_path.stem + ".lex")
create_lex_file(translations, lex_file_name)