英文字幕確實讓人頭疼,因此,花了一天專門研究,用python實現了比較簡單的翻譯程式碼。僅有幾十行
首先載入模組
pip uninstall googletrans
git clone https://github.com/BoseCorp/py-googletrans.git
cd ./py-googletrans && python setup.py install
使用測試
from googletrans import Translator
# 範例化
translator = Translator(service_urls=['translate.google.cn'])
content = 'Today is a gooday'
print(translator.translate(content, dest='zh-CN').text.encode('utf-8').decode('utf-8'))
輸出沒問題就行
思路:
按行讀取檔案內容,翻譯特定行的字幕即可,非常簡單,但是要注意編碼問題
from googletrans import Translator
# encoding=utf-8
import argparse
def main(args):
# 範例化
translator = Translator(service_urls=['translate.google.cn'])
f = open(args.fs, 'r+', encoding="utf-8")
flist = f.readlines()
f = open(args.fs, 'w+', encoding="utf-8")
f.writelines(flist)
for x in range(4, len(flist)):
if x % 4 == 0:
print(x)
flist[x] = translator.translate(flist[x], dest='zh-CN').text.encode('utf-8').decode('utf-8') + "\n"
print(translator.translate(flist[x], dest='zh-CN').text.encode('utf-8').decode('utf-8'))
f = open(args.fs, 'w+', encoding="utf-8")
f.writelines(flist)
if __name__ == '__main__':
parser = argparse.ArgumentParser(usage="it's usage tip.", description="help info.")
parser.add_argument("--fs", type=str, required=True, help="the fileloacation")
args = parser.parse_args()
main(args)
使用示範:
python tran.py --fs "D:\xiaxiaxia\pycharmtext\a.vtt"
注意事項
讀行,按行處理,然後寫入和開啟都要注意編碼,寫入的時候還得再最後加個換行符\n 這樣才不會有錯誤。
程式碼還是比較簡單,感興趣的可以在io處理和並行上還可以再優化。