Ad

Aligning Sentences In A Text.txt File Using Open() Function And Str.join And Split Method

- 1 answer

I am trying to modify (align sentences in a document) a text in a file using python. I tried the following approach with no success. I don't care if the txt is modified or I can get python to read the aligned sentences in the console. Regardless if I use w or r I get an error.

The document contains the following text: "Hello world. Goodbye world."

document = open("text.txt", "w")

def sentence_separator(document):
    sentences = document.split(". ")
    return "\n".join(sentences)

document.close()

The desired output or text modification is:

Hello world

Goodbye world

Any suggestions? Appreciate it.

Ad

Answer

You can't do: sentences = document.split(". "). It's the equivalent of:

sentences = file(open('text.txt'), 'w').split()

Which won't work because .split() only works for strings.

You need to do: sentences = document.read().split(). Don't forget to use 'r+' flag to open() as well.

So overall, you have something like this:

f = open("text.txt", "r+")
document = open("text.txt", "r+").read()
sentences = document.split(". ")
f.write("\n".join(sentences))
f.close()

So, if input file is:

Hello world. Goobye world.

Then the output file will become:

Hello world
Goodbye world.
Ad
source: stackoverflow.com
Ad