原因:
QT项目中,发现QTextEdit QPlainTextEdit的右键菜单翻译不全,跟踪代码发现是未翻译qtbase.ts的QWidgetTextControl节点,且未见有qtbase_CN.ts版本。
然后就以日文版的qtbase_ja.ts为模板,把QWidgetTextControl节点翻译到qt_zh_CN.ts中,在编译为二进制用于项目中。
注意:u"###5 Translate escape character." 这个模块的功能是还原xml节点的text含' "时,在编程xml时会被转义为"&;"的问题。
用法:
call merge_translate.py "\src\qtbase_ja.ts" "\src\qt_zh_CN_.ts" "\src\qt_zh_CN.ts"
代码:
#coding=utf-8
from bs4 import BeautifulSoup
import lxml
import re
import os,sys
'''
<context>
<name>CloseButton</name>
<message>
<source>Close Tab</source>
<translation>xxxxxxxxxxxxxxxxxxx</translation>
</message>
</context>
'''
def doTranslate(pathJa, pathCNTemp, pathCN):
print pathJa, pathCNTemp, pathCN
#os.system("pause")
print u"###1 read Translation file."
contentsJA= ""
with open(pathJa) as f:
for line in f.readlines():
contentsJA += line
soupJA = BeautifulSoup(contentsJA, "xml")
print u"###2 get Translation node."
listContents = [ item for item in soupJA.find_all('context') if item('name')[0].contents[0] == u'QWidgetTextControl']
if 0 == len(listContents):
print u" QWidgetTextControl not exist,return"
return
#清空原来的翻译内容
QWidgetTextControlContents = listContents[0]
for item in listContents[0].findChildren('message'):
item('translation')[0].contents[0]=u''
print u"###3 insert Translation node."
contentsCN= ""
with open(pathCNTemp) as f:
for line in f.readlines():
contentsCN += line
soupCN = BeautifulSoup(contentsCN, "xml")
listContentsCN = [ item for item in soupCN.find_all('context') if item('name')[0].contents[0] == u'QWidgetTextControl']
if 0 == len(listContentsCN):
lastContents = soupCN.find_all('context')[-1]
lastContents.insert_after(QWidgetTextControlContents)
print u"###4 Translate null word entry."
for item in soupCN.find_all('context')[-1].findChildren('message'):
if 0 == len(item.translation.contents[0]):
listTemp = [train for train in soupCN.find_all('message') if item.source.contents[0] == train.source.contents[0] and 0 != len(train.translation.contents[0])]
#print listTemp
if len(listTemp) > 0:
temp = listTemp[0]
item.translation.contents[0] = temp.translation.contents[0]
print u"###5 Translate escape character."
t = str(soupCN)
while re.findall( r"(>.*?)'", t ):
t = re.sub(r"(>.*?)'", r"\1'", t)
while re.findall( '''(>.*?)\"''', t ):
t = re.sub('''(>.*?)\"''', r"\1"", t)
print u"###6 save file."
fo = open(pathCN, "w+")
fo.write( t)
fo.close()
if __name__ == "__main__":
#print sys.argv
print sys.getdefaultencoding()
if 4 > len(sys.argv):
print u"please input qtbase_ja.ts qt_zh_CN_.ts qt_zh_CN.ts full path."
else:
doTranslate(sys.argv[1], sys.argv[2], sys.argv[3])