0

I want to count the total no of words in each line in a file and print them.I tried

with codecs.open('v.out','r',encoding='utf-8') as f:
    for line in f.readlines():
        words = len(line.strip(' '))
        print words

the input file is:

hello 
try it
who knows
it may work

the output that I get is:

6
7
10
12

but what I need is:

1 
2 
2
3

is there any function that I can use? I have to print the first word of each line in a file, and similarly print the middle word and the last word of the line into separate files.

charvi
  • 211
  • 1
  • 5
  • 16

2 Answers2

4

You are stripping spaces from the ends, not splitting the words. You are counting the remaining characters now, not words.

Use str.split() instead:

words = len(line.split())

No arguments required, or use None; it'll strip whitespace from the ends, and split on arbitrary-width whitespace, giving you words:

>>> 'it may work'.split()
['it', 'may', 'work']
>>> len('it may work'.split())
3
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

You were so close. This line:

words = len(line.strip(' '))

should be:

words = len(line.split(' '))

strip removes characters from the start and end of the string, split breaks the string up into a list of strings.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437