python - 如何在 python 中翻译文本?
问题描述
如何在 python 中翻译文本?
如果我在 .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) 模块是可能的。以下代码采用您提供的格式文本文件的输入文件夹(允许多次出现),翻译相关部分并在输出文件夹中为每个输入文件创建一个新的翻译文本文件。
请注意,谷歌翻译的准确性并不为人所知。
googletrans 翻译了你的例子:
“完成黑彼得案。” 到“Valmis Musta Pekka 小吃”。
“是啊是啊,队长!” “爱爱,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()
推荐阅读
- tensorflow - 使用 tff-nightly 时,“tensorflow_federated.python.simulation”没有属性“FromTensorSlicesClientData”
- powerbi-desktop - 谷歌驱动器数据集的powerBI仪表板
- javascript - 在循环中反应谷歌地图唯一键错误
- html -
doesn't behave like it should (I think) in HTML5</h1> <div id="body"><p>I am learning HTML5 (so don't judge me) and I came across something that doesn't make much sense to me.</p> <p>How come that when I put the title - eclipse - 错误:找不到包 org.globalplatform 的导出文件 globalplatform.exp。我没有找到将 exp 文件放在 eclipse 中的位置
- html - style.css 更新不适用于某些代码
- postman - 在 PKCE 流程中从 OKTA 获取访问令牌,无需用户交互
- jquery - 为什么 jquery .children() 忽略“td”标签?
- python - ImportError:无法确定 xlrd 的版本(尝试读取 excel)
- javascript - 带有过渡的页面滚动后的居中元素