Python Forum

Full Version: Python - Limit Sentence Length to 10 Words - Text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to limit each sentence to 10 words


file = open("a.txt","r") 
content = file.read()
file.close()

file_out = open("out.txt","w+") 

for i in range(len(content)):
    file_out.write(content[i])

   

    if (i + 1).join(i.split()[:10]):
        

         file_out.write('\n')
file_out.close()
what would be the correct syntax?
Try to use the context manage with when manipulate files.

Check if this is what you want:
with open("a.txt", "r") as f_in:
    with open("out.txt", "w+") as f_out:
        for line in f_in:
            words = line.split(' ')[:10]
            f_out.write(' '.join(words) + '\n')
Thank you GJ,

that did the trick

Have a great weekend!