Python - Limit Sentence Length to 10 Words - Text file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Python - Limit Sentence Length to 10 Words - Text file (/thread-11680.html) |
Python - Limit Sentence Length to 10 Words - Text file - dj99 - Jul-21-2018 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? RE: Python - Limit Sentence Length to 10 Words - Text file - gontajones - Jul-21-2018 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') RE: Python - Limit Sentence Length to 10 Words - Text file - dj99 - Jul-21-2018 Thank you GJ, that did the trick Have a great weekend! |