简体   繁体   中英

How do i translate text in python?

How do i translate text in python?

If i have text in a.int file and i would like to translate parts "Aye Aye, Captain." and "Finish Black Peter case?" to Finnish and replace them to a new file how would i do it with the same format?

[finishbp Data_FDK_Achievement]
LocName="Aye Aye, Captain!"
LocDescription="Finish Black Peter case."

The finished product should look like this

[finishbp Data_FDK_Achievement]
LocName="Aye Aye, kapteeni!"
LocDescription="Viimeistele Black Peter-tapaus."

With the googletrans (pypi.org/project/googletrans) module that is possible. The following code takes an input folder with text files of the format you provided (multiple occurrences are allowed), translates the relevant parts and creates a new translated text file in the output folder for every input file.
Please be aware that google translate is not known for its accuracy.
googletrans translated your examples:
"Finish Black Peter case." to "Valmis Musta Pekka tapaus."
"Aye Aye, Captain," to "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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM