Bottom Page

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
Quote
#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')
dj99 likes this post
Quote
#3
Thank you GJ,

that did the trick

Have a great weekend!



:)


Python newbie trying to learn the ropes
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  length constraint on phrase hash to password javaben 0 22 47 minutes ago
Last Post: javaben
  python file output to log file Rsh 4 180 Aug-13-2019, 09:00 PM
Last Post: DeaD_EyE
  Camera animation to Text file (CINEMA 4D) vbz 0 75 Aug-13-2019, 07:39 AM
Last Post: vbz
  Restrict / Limit variable size mln4python 4 128 Aug-13-2019, 07:17 AM
Last Post: mln4python
  Python QGIS tool that replaces layout text labels with attributes from an input table geodenn92 1 90 Aug-13-2019, 06:05 AM
Last Post: buran
  read text file and write into html with correct link jacklee26 4 154 Aug-02-2019, 05:48 AM
Last Post: jacklee26
  Four text files input combinations into an output file mhyga 2 148 Jul-28-2019, 06:52 PM
Last Post: ThomasL
  Read a remote text file Sandy7771989 1 162 Jul-18-2019, 06:55 PM
Last Post: ndc85430
  Trying to make column based file from text file scor1pion 7 213 Jul-16-2019, 02:43 PM
Last Post: scor1pion
  Running python from Sublime Text editor balley810 2 159 Jul-14-2019, 03:40 PM
Last Post: ThomasL

Forum Jump:


Users browsing this thread: 1 Guest(s)