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
#1
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?



:)


Python newbie trying to learn the ropes
Reply
#2
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')
Reply
#3
Thank you GJ,

that did the trick

Have a great weekend!



:)


Python newbie trying to learn the ropes
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  getting the length of a file in a loop sgcgrif33 1 287 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 399 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Open and read multiple text files and match words kozaizsvemira 3 4,276 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,064 Apr-16-2021, 01:47 AM
Last Post: MDRI
  while sentence kimyyya 3 913 Mar-20-2021, 06:00 AM
Last Post: Pedroski55
  Increment text files output and limit contains Kaminsky 1 882 Jan-30-2021, 06:58 PM
Last Post: bowlofred
  List / arrays putting in sentence Kurta 3 867 Dec-25-2020, 11:29 AM
Last Post: Larz60+
  [split] How to convert the CSV text file into a txt file Pinto94 5 1,044 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,426 Nov-16-2020, 07:56 AM
Last Post: Gribouillis
  Counting the most relevant words in a text file caiomartins 2 826 Sep-21-2020, 08:39 AM
Last Post: caiomartins

Forum Jump:

User Panel Messages

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