如何使用 Python 对大型文本文件进行双重翻译?
How to do a double translation of a large text file using Python?
我有一个大小为 2 x 400000 的 text.csv
文件,如下所示:
col 1 col2
0 text text
1 text text
2 text text
...
399999 text text
400000 text text
每列都需要从英文翻译成法文,然后再翻译回英文。我尝试使用 Google Translate 手动执行此操作,但我的文件大小为 60MB,而 Google Translate 仅支持最大 1 MB 的文件。
能否使用 Python 以某种方式自动完成此 Eng > Fr > Eng 翻译?
您可以尝试以下操作来读取 csv 文件,并且文件中每一行的两列都从英语翻译成法语再翻译回英语:
import csv
from google.cloud import translate
translate_client = translate.Client()
def translateFunction(text,target):
translation = translate_client.translate(text,target_language=target)
return (translation['translatedText'])
output_file = open('output.csv', 'wb')
reader = csv.reader(open('source.csv', 'rU'), dialect=csv.excel_tab,delimiter=',')
for row in reader:
column1=translateFunction(translateFunction(row[1],'fr'),'en')
column2=translateFunction(translateFunction(row[2],'fr'),'en')
output_text = ','.join([row[0],column1,column2])
output_file.write(output_text.encode('utf-8')+'\n')
output_file.close()
请记住,这会对翻译提出多个请求 API。
我有一个大小为 2 x 400000 的 text.csv
文件,如下所示:
col 1 col2
0 text text
1 text text
2 text text
...
399999 text text
400000 text text
每列都需要从英文翻译成法文,然后再翻译回英文。我尝试使用 Google Translate 手动执行此操作,但我的文件大小为 60MB,而 Google Translate 仅支持最大 1 MB 的文件。
能否使用 Python 以某种方式自动完成此 Eng > Fr > Eng 翻译?
您可以尝试以下操作来读取 csv 文件,并且文件中每一行的两列都从英语翻译成法语再翻译回英语:
import csv
from google.cloud import translate
translate_client = translate.Client()
def translateFunction(text,target):
translation = translate_client.translate(text,target_language=target)
return (translation['translatedText'])
output_file = open('output.csv', 'wb')
reader = csv.reader(open('source.csv', 'rU'), dialect=csv.excel_tab,delimiter=',')
for row in reader:
column1=translateFunction(translateFunction(row[1],'fr'),'en')
column2=translateFunction(translateFunction(row[2],'fr'),'en')
output_text = ','.join([row[0],column1,column2])
output_file.write(output_text.encode('utf-8')+'\n')
output_file.close()
请记住,这会对翻译提出多个请求 API。