首页 > 解决方案 > 如何在 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."

标签: pythonlanguage-translation

解决方案


使用 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()

推荐阅读