-2

I have a text file of following type-

 
eng Firstly, in the course of the last few decades the national eng Secondly, the national courts will be empowered to implement eng However, I am convinced of the fact that the White Paper has put us on the right path.

I want to restrict the length of each line upto (say) 9 words. I tried of using python's read_line method but it specifies the size of the line only.I am unable to find any other suitable method. How to do it ?

Sample Output-

eng Firstly, in the course of the last few
eng Secondly, the national courts will be empowered to
eng However, I am convinced of the fact that 
Bing
  • 631
  • 1
  • 8
  • 23

2 Answers2

5

To get the first n words of a string as a string:

def first_n_words(s, n):
    return ' '.join(s.split()[:n])
MegaBluejay
  • 426
  • 2
  • 8
1

You could make a list of each word like so:

with open(file, 'r') as f:
    lines = []
    for line in f:
        lines.append(line.rstrip('\n').split())

Now limit each line to 9 by using slicing which truncated automatically:

with open(file, 'w') as f:
    for line in lines:
        f.write(' '.join(line[:9]))
        f.write('\n')
N Chauhan
  • 3,407
  • 2
  • 7
  • 21