如何翻译python中的文本?

2024-06-28 19:49:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如何翻译python中的文本

如果我有一个.int文件中的文本,我想将“是的,船长!”和“完成黑彼得案”的部分翻译成芬兰语,并替换成一个新文件,我将如何使用相同的格式

[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."

Tags: 文件文本data格式peterintblack船长
1条回答
网友
1楼 · 发布于 2024-06-28 19:49:30

使用googletrans(pypi.org/project/googletrans)模块,这是可能的。以下代码获取一个输入文件夹,其中包含您提供的格式的文本文件(允许多次出现),翻译相关部分,并在输出文件夹中为每个输入文件创建一个新的翻译文本文件
请注意,谷歌翻译并不以其准确性著称
googletrans将您的示例翻译为:
“完成黑彼得案”到“Valmis Musta Pekka tapaus”。
“是的,船长!”到“哎,哎,卡普蒂尼!”

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

相关问题 更多 >