0

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.

sunflower
  • 19
  • 4
  • 1
    The len(gth) of a word is how many letters are in it, not how many words there are, you should count them instead, make a counter variable that you increment yourself for example. – Sayse Jun 24 '21 at 11:54
  • 1
    use `collections.Counter` – mujjiga Jun 24 '21 at 11:57

1 Answers1

0

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))
blueteeth
  • 3,330
  • 1
  • 13
  • 23