Home > Net >  Python - Translate a file and keep original paragraph spacing
Python - Translate a file and keep original paragraph spacing

Time:10-01

I have this project I am working on but need help. My main goal is to make the translated text file look the same as the original file with the exception of the translated words.

Here is what a snippet of the original file looks like:

Original Text File

Here is my python code:

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

And lastly, here is what my output looks like:

Output Translated File

As you can see, I was able to translate the file but the original spacing is ignored. How do I change my code to keep the spacing as it was before?

CodePudding user response:

You can keep the spaces by reading one line at a time.

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)

CodePudding user response:

I'd suggest combining steps 3 and 4 to translate each line and write the line and then \n to start the next line.

I haven't checked the following on a compiler so you might have to modify it to get it to work.

Note I changed the 'w' to 'a' so it appends instead of just writes and afaik using 'with' means the file will close so you don't need the explicit 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")
  • Related