【问题标题】:Python - Translate a file and keep original paragraph spacingPython - 翻译文件并保持原始段落间距
【发布时间】:2021-11-22 15:25:33
【问题描述】:

我正在处理这个项目,但需要帮助。我的主要目标是使翻译后的文本文件看起来与原始文件相同,但翻译后的单词除外。

原始文件的 sn-p 如下所示:

Original Text File

这是我的python代码:

# Step 1: Import the english.txt file

import json

english_text = open('/home/jovyan/english_to_lolspeak_fellow/english.txt', 'r')

text = english_text.readlines()

english_text.close()

# Step 2: Import the glossary (the tranzlashun.json file)

with open('/home/jovyan/english_to_lolspeak_fellow/tranzlashun.json') as translationFile:
    data = json.load(translationFile)
# Step 3:Translate the English text into Lolspeak

translated_text= ''

for line in text:
    for word in line.split():
        if word in data:
            translated_text += data[word.lower()]+" "
        else:
            translated_text += word.lower()+ " "
pass
# Step 4 :Save the translated text as the "lolcat.txt" file

with open('/home/jovyan/english_to_lolspeak_fellow/lolcat.txt', 'w') as lolcat_file:

    lolcat_file.write(translated_text)

lolcat_file.close()

最后,我的输出如下所示:

Output Translated File

如您所见,我能够翻译文件,但忽略了原始间距。如何更改我的代码以保持原来的间距?

【问题讨论】:

    标签: python for-loop readlines writefile


    【解决方案1】:

    您可以通过一次读取一行来保留空格。

    with open('lolcat.txt', 'w') as fw, open('english.txt') as fp:
        for line in fp:
            for word in line.split():
                line = line.replace(word, data.get(word.lower(), word))
            fw.write(line)
    

    【讨论】:

      【解决方案2】:

      我建议将第 3 步和第 4 步结合起来翻译每一行并编写该行,然后 \n 开始下一行。

      我没有在编译器上检查以下内容,因此您可能需要对其进行修改才能使其正常工作。

      请注意,我将“w”更改为“a”,因此它会追加而不是仅写入,而使用“with”的 afaik 意味着文件将关闭,因此您不需要显式 close()。

      for line in text:
          translated_line = ""
          for word in line.split():
              if word in data:
                  translated_line += data[word.lower()]+" "
              else:
                  translated_line += word.lower()+ " "
          with open('/home/jovyan/english_to_lolspeak_fellow/lolcat.txt', 'a') as lolcat_file:
              lolcat_file.write(translated_line)
              write("\n")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-01
        • 2020-05-10
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2018-06-25
        • 1970-01-01
        相关资源
        最近更新 更多