pytex/default_formatters/dictionary_formatter.py

72 lines
2.7 KiB
Python

import datetime
from pathlib import Path
from typing import Dict, Optional, List
from datetime import *
import csv
class DictionaryFormatter:
def __init__(self, kind: str, author: str, header: Optional[List[str]]):
self.header = header
self.kind = kind.lower()
self.author = author
author_parts = self.author.lower().replace('ß', 'ss').split(' ')
self.author_acronym = author_parts[0][0] + author_parts[-1]
self.dictname = r'translator-{kind}-dictionary'.format(
kind=self.kind
)
self.name_lowercase = self.dictname + '-{language}'
self.file_name = self.name_lowercase + '.dict'
self.date = datetime.now().strftime('%Y/%m/%d')
self.year = int(datetime.now().strftime('%Y'))
self.replace_dict: Dict = {}
self.arg_replace_dict: Dict = {}
self.source_file_name = "not specified"
@property
def filename(self):
return self.file_name
def format_file(self, input_path: Path, output_dir: Path = None):
self.source_file_name = str(input_path.name)
if self.header:
lines = '%' * 80 + '\n' \
+ '\n'.join(map(lambda line: '% ' + line, self.header)) \
+ '\n' + '%' * 80 + '\n\n'
else:
lines = []
if output_dir is None:
output_dir = input_path.parent
output_dir.mkdir(parents=True, exist_ok=True)
with open(input_path, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
langs = next(spamreader)
translations = {}
for lang in langs[1:]:
translations[lang] = {}
for line in spamreader:
for n in range(1, len(line)):
translations[langs[n]][line[0]] = line[n]
for lang in langs[1:]:
lang_lines = lines
lang_lines += r'\ProvidesDictionary{{{dictname}}}{{{lang}}}'.format(
dictname=self.dictname,
lang=lang
)
lang_lines += '\n'
lang_lines += '\n'
for key in translations[lang].keys():
if translations[lang][key].strip() != '':
lang_lines += r'\providetranslation{{{key}}}{{{translation}}}'.format(
key=key.strip(),
translation=translations[lang][key].strip()
)
lang_lines += '\n'
(output_dir / self.file_name.format(language=lang)).write_text(''.join(lang_lines))
def make_default_macros(self):
pass