如何翻译python中的文本?

dauxcl2d  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(186)

如何翻译python中的文本?
如果我在一个.int文件中有文本,我想把部分“是啊,船长!”和“完成黑彼得案件。”芬兰语,并将它们替换为一个新的文件,我将如何做它与相同的格式?

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

完成的产品应如下所示

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

zqry0prt1#

下面的代码获取一个输入文件夹,其中包含您提供的格式的文本文件(允许多次出现),翻译相关部分,并在输出文件夹中为每个输入文件创建一个新的翻译文本文件。
请注意,谷歌翻译是不知道它的准确性。
googletrans翻译了你的例子:
"完成黑彼得的案子"改成"瓦尔米斯·穆斯塔·佩卡·塔帕乌斯. "
“是啊,船长!”到“哎,卡皮蒂尼!”

  1. from googletrans import Translator
  2. import os
  3. import re
  4. INPUT_FOLDER_PATH = 'path/to/inputFolder'
  5. OUTPUT_FOLDER_PATH = 'path/to/outputFolder'
  6. # a translator object from the googletrans api
  7. tl = Translator()
  8. # go through all the files in the input folder
  9. for filename in os.listdir(INPUT_FOLDER_PATH):
  10. # open the file to translate and split the data into lines
  11. in_file = open(f'{INPUT_FOLDER_PATH}/{filename}', 'r')
  12. data = in_file.read()
  13. data = data.split('\n')
  14. # the modified data string we will now fill
  15. transl_data = ""
  16. # translate the relevant parts of each line
  17. for line in data:
  18. # find matches: is this a relevant line?
  19. locname = re.findall('(?<=LocName=").*(?=")', line)
  20. locdesc = re.findall('(?<=LocDescription=").*(?=")', line)
  21. # if there is a locName or locDescription match, translate the important part and replace it
  22. if len(locname) == 1:
  23. locname_trans = tl.translate(locname[0], dest='fi').text
  24. line = re.sub('(?<=LocName=").*(?=")', locname_trans, line)
  25. elif len(locdesc) == 1:
  26. locdesc_trans = tl.translate(locdesc[0], dest='fi').text
  27. line = re.sub('(?<=LocDescription=").*(?=")', locdesc_trans, line)
  28. # add the translated line to the translated string
  29. transl_data += line + '\n'
  30. # create a new file for the translations
  31. out_file = open(f'{OUTPUT_FOLDER_PATH}/{filename}-translated', 'w')
  32. # write the translated data to the output file
  33. out_file.write(transl_data)
  34. # clean up
  35. in_file.close()
  36. out_file.close()
展开查看全部

相关问题