python中是否有处理TMX(Translation Memory eXchange)文件的模块,如果没有,还有什么其他方法?
目前,我有一个巨大的2gb文件,有法语和英语字幕。有可能处理这样一个文件吗?还是我必须把它分解?
正如@hurrial所说,您可以使用翻译工具包。
安装
此工具包只能使用pip。要安装它,请运行:
pip install translate-toolkit
用法
假设您有以下简单的sample.tmx
文件:
<tmx version="1.4">
<header
creationtool="XYZTool" creationtoolversion="1.01-023"
datatype="PlainText" segtype="sentence"
adminlang="en-us" srclang="en"
o-tmf="ABCTransMem"/>
<body>
<tu>
<tuv xml:lang="en">
<seg>Hello world!</seg>
</tuv>
<tuv xml:lang="ar">
<seg>اهلا بالعالم!</seg>
</tuv>
</tu>
</body>
</tmx>
你可以这样解析这个简单的文件:
>>> from translate.storage.tmx import tmxfile
>>>
>>> with open("sample.tmx", 'rb') as fin:
... tmx_file = tmxfile(fin, 'en', 'ar')
>>>
>>> for node in tmx_file.unit_iter():
... print(node.source, node.target)
Hello world! اهلا بالعالم!
有关更多信息,请查看此处的官方文档。
您可以查看以下链接:
- 预传输:http://translate-toolkit.readthedocs.org/en/latest/commands/pretranslate.html
- 翻译工具包:http://en.wikipedia.org/wiki/Translate_Toolkit
- 翻译工具包包:https://pypi.python.org/pypi/translate-toolkit
- 翻译API:https://github.com/translate/translate
干杯,
以下是一个可以轻松将TMX转换为pandas数据帧的脚本:
from collections import namedtuple
import pandas as pd
from tqdm import tqdm
from bs4 import BeautifulSoup
def tmx2df(tmxfile):
# Pick your poison for parsing XML.
with open(tmxfile) as fin:
content = fin.read()
bsoup = BeautifulSoup(content, 'lxml') # Actual TMX extraction.
lol = [] # Keep a list of the rows to populate.
for tu in tqdm(bsoup.find_all('tu')):
# Parse metadata from tu
metadata = tu.attrs
# Parse prop
properties = {prop.attrs['type']:prop.text for prop in tu.find_all('prop')}
# Parse seg
segments = {}
# The order of the langauges might not be consistent,
# so keep them in some dict and unstructured first.
for tuv in tu.find_all('tuv'):
segment = ' '.join([seg.text for seg in tuv.find_all('seg')])
segments[tuv.attrs['xml:lang']] = segment
lol.append({'metadata':metadata, 'properties':properties, 'segments':segments}) # Put the list of rows into a dataframe.
df = pd.DataFrame(lol) # See https://stackoverflow.com/a/38231651
return pd.concat([df.drop(['segments'], axis=1), df['segments'].apply(pd.Series)], axis=1)