前段時間做公司一個自動翻譯項目需要處理大量的文案字段,手工去做簡直不大可能(懶),因此借用python腳本自動化處理掉了,在此記錄一下。
import linecache
def outputfile(i,j,n):
# zh = file_zh.read().decode('utf-8').encode('gbk', 'ignore')
file_new = open ('1.txt', 'r+')
for l in range(i,j+1):
# line = linecache.getline('tw.txt', l).decode('utf-8').encode('gbk', 'ignore')
line1 = str(linecache.getline('zh.txt', l)[0:-1]).strip()
line2 = str(linecache.getline('tw.txt', l+n)[0:-1]).strip()
if(len(str(line1[0:-1]))==0):
continue
file_new.write('msgid "'+ line1 +'"\n')
file_new.write('msgstr "'+ line2 +'"\n\n')
file_new.close()
outputfile(1,25,3)
生成效果:
# 這些是測試字段 msgid "Hello world!" msgstr "世界你好!" msgid "Python is a good Language." msgstr "Python 是門好語言." msgid "中國" msgstr "中國" msgid "測試啊" msgstr "測試呢!!!" msgid "Hello %(useraaa)s!" msgstr "你好 %(useraaa)s!"
代碼非常簡單,過程為從兩個不同文件里一行一行地讀取字符,再按照一定格式一行一行地輸出到新文件中,需要注意的是,txt文件需要保存為UTF-8編碼格式,否則需要轉碼,有點麻煩~
