Python Forum
Python - Limit Sentence Length to 10 Words - Text file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python - Limit Sentence Length to 10 Words - Text file
I am trying to limit each sentence to 10 words

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

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

for i in range(len(content)):


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

what would be the correct syntax?


Python newbie trying to learn the ropes
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!


Python newbie trying to learn the ropes

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extract a string between 2 words from a text file OscarBoots 2 255 Nov-02-2021, 08:50 AM
Last Post: ibreeden
  getting the length of a file in a loop sgcgrif33 1 401 Aug-23-2021, 05:11 PM
Last Post: deanhystad
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 537 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Open and read multiple text files and match words kozaizsvemira 3 4,529 Jul-07-2021, 11:27 AM
Last Post: Larz60+
  How to make a test data file for the full length of definition? MDRI 6 1,244 Apr-16-2021, 01:47 AM
Last Post: MDRI
  while sentence kimyyya 3 1,080 Mar-20-2021, 06:00 AM
Last Post: Pedroski55
  Increment text files output and limit contains Kaminsky 1 1,080 Jan-30-2021, 06:58 PM
Last Post: bowlofred
  List / arrays putting in sentence Kurta 3 987 Dec-25-2020, 11:29 AM
Last Post: Larz60+
  [split] How to convert the CSV text file into a txt file Pinto94 5 1,212 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Saving text file with a click: valueerror i/o operation on closed file vizier87 5 1,583 Nov-16-2020, 07:56 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020