| import pandas as pd |
| import xmltodict |
| from sklearn.model_selection import train_test_split |
| import glob |
| import sys |
|
|
| filelist = glob.glob('tmx/*.tmx') |
|
|
| for tmxfile in filelist: |
| print(f"Starting to parse {tmxfile}") |
|
|
| verbose = 0 |
| with open(tmxfile) as fd: |
| doc = xmltodict.parse(fd.read()) |
| |
| try: |
| |
| source = doc['tmx']['body']['tu'][0]['tuv'][0]['@xml:lang'] |
| target = doc['tmx']['body']['tu'][1]['tuv'][1]['@xml:lang'] |
| except: |
| source = doc['tmx']['body']['tu'][0]['tuv'][0]['@lang'] |
| target = doc['tmx']['body']['tu'][1]['tuv'][1]['@lang'] |
|
|
| |
| data=[] |
| errorcount = 0 |
| for item in doc['tmx']['body']['tu'][:]: |
| trans = {} |
| valid = 1 |
| trans[source] = item['tuv'][0]['seg'] |
| trans[target] = item['tuv'][1]['seg'] |
| if isinstance(trans[source],dict): |
| try: |
| trans[source] = trans[source]['#text'] |
| trans[target] = trans[target]['#text'] |
| except: |
| if verbose: |
| print("Dropping - Malformed XML") |
| valid = 0 |
| |
| if not trans[source] or not trans[target]: |
| valid = 0 |
| if verbose: |
| print("Dropping source/target does not exist") |
|
|
| elif len(trans[source]) <= 1 or len(trans[target]) <=1: |
| valid = 0 |
| if verbose: |
| print("Dropping - Partly empty entity") |
|
|
| elif '\t' in trans[source] or '\t' in trans[target]: |
| valid = 0 |
| if verbose: |
| print("Dropping - Contains tabulator") |
|
|
|
|
| if valid == 1: |
| data.append(trans) |
| else: |
| errorcount += 1 |
|
|
| |
| df = pd.DataFrame(data) |
|
|
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| if source=="fi": |
| source="fin" |
| if target=="fi": |
| target="fin" |
| if source=="nb": |
| source="nob" |
| if target=="nb": |
| target="nob" |
| if source=="se": |
| source="sme" |
| if target=="se": |
| target="sme" |
|
|
| filename = "tsv_source_target/"+source+target+".tsv" |
| df.to_csv(filename, index=False, header=False, sep='\t') |
|
|
| |
| print(f"Finished writing {filename} ({len(df)}) to disk.") |
| print(f"Totally {errorcount} errors") |
|
|
|
|
|
|
|
|