I am trying to print a file's word count so I could parase it to q.put()
. I am calling:
with open('medium.txt', 'r') as f:
for word in f:
print(len(word))
Exept I get this:
11
3
7
5
7
But what I want is this:
1
2
3
4
5
I want the total number of words printed in order from 1
to however much words there are.
Good job iterating over f
. This is the right way to do it as you don't load the entire file into memory as others are suggesting.
You're pretty close, it's just that what you have as word
is actually a line. You need to split that line by whitespace, and then count the words.
with open('medium.txt', 'r') as f:
for line in f:
words = line.split()
print(len(words))
You count the letters of the words, not the words itselfes.
text = file.read()
text = text.split(" ")
nZ = 0
for word in text:
nZ += 1
print(nZ)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.