python - How to count and print the number of words in each line in a file? -
this question has answer here:
i want count total no of words in each line in file , print them.i tried
with codecs.open('v.out','r',encoding='utf-8') f: line in f.readlines(): words = len(line.strip(' ')) print words
the input file is:
hello try knows may work
the output is:
6 7 10 12
but need is:
1 2 2 3
is there function can use? have print first word of each line in file, , print middle word , last word of line separate files.
you close. line:
words = len(line.strip(' '))
should be:
words = len(line.split(' '))
strip
removes characters start , end of string, split
breaks string list of strings.
Comments
Post a Comment