[英]How do i translate text in python?
如何翻譯 python 中的文本?
如果我在 a.int 文件中有文本並且我想翻譯部分“Aye Aye, Captain”。 和“完成黑彼得案?” 到芬蘭語並將它們替換為新文件我將如何使用相同的格式?
[finishbp Data_FDK_Achievement]
LocName="Aye Aye, Captain!"
LocDescription="Finish Black Peter case."
成品應該是這樣的
[finishbp Data_FDK_Achievement]
LocName="Aye Aye, kapteeni!"
LocDescription="Viimeistele Black Peter-tapaus."
使用 googletrans (pypi.org/project/googletrans) 模塊是可能的。 以下代碼采用您提供的格式文本文件的輸入文件夾(允許多次出現),翻譯相關部分並在 output 文件夾中為每個輸入文件創建一個新的翻譯文本文件。
請注意,谷歌翻譯的准確性並不為人所知。
googletrans 翻譯了你的例子:
“完成黑彼得案。” 到“Valmis Musta Pekka 小吃”。
“Aye Aye,船長”到“Ai-ai,kapteeni!”
from googletrans import Translator
import os
import re
INPUT_FOLDER_PATH = 'path/to/inputFolder'
OUTPUT_FOLDER_PATH = 'path/to/outputFolder'
# a translator object from the googletrans api
tl = Translator()
# go through all the files in the input folder
for filename in os.listdir(INPUT_FOLDER_PATH):
# open the file to translate and split the data into lines
in_file = open(f'{INPUT_FOLDER_PATH}/{filename}', 'r')
data = in_file.read()
data = data.split('\n')
# the modified data string we will now fill
transl_data = ""
# translate the relevant parts of each line
for line in data:
# find matches: is this a relevant line?
locname = re.findall('(?<=LocName=").*(?=")', line)
locdesc = re.findall('(?<=LocDescription=").*(?=")', line)
# if there is a locName or locDescription match, translate the important part and replace it
if len(locname) == 1:
locname_trans = tl.translate(locname[0], dest='fi').text
line = re.sub('(?<=LocName=").*(?=")', locname_trans, line)
elif len(locdesc) == 1:
locdesc_trans = tl.translate(locdesc[0], dest='fi').text
line = re.sub('(?<=LocDescription=").*(?=")', locdesc_trans, line)
# add the translated line to the translated string
transl_data += line + '\n'
# create a new file for the translations
out_file = open(f'{OUTPUT_FOLDER_PATH}/{filename}-translated', 'w')
# write the translated data to the output file
out_file.write(transl_data)
# clean up
in_file.close()
out_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.