calamri
calamri

Reputation: 41

Word counter (Introduction to Programming 2(python))

I tried looking for an answer to this problem but it didn't work. (btw I am 15 and basically just started python) This is my program:

all = []

count = {}

line = input("Enter line: ")

while line:

    word = line.split()

    line = input("Enter line: ")

for w in word:

    if w in count:

        count[w] += 1

    else:

        count[w] = 1

for word in sorted(count):

    print(word, count[word])

This is the answer I'm getting:

Enter line: which witch
Enter line: is which
Enter line: 
is 1
which 1

When I should be getting:

Enter line: which witch
Enter line: is which
Enter line: 
is 1
which 2
witch 1

Please, can someone help?

Upvotes: 4

Views: 1126

Answers (2)

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

Here is way using Counter from collections module, it will give a dict with list elements as key at its frequency as values, it may help you to reduce the code length and use of for loop, You can get more idea about Counter from here :

from collections import Counter

all = []
line = input("Enter line: ")
while line:
    all.extend(line.split())
    line = input("Enter line : ")

for i,j in Counter(all).items():
    print(i, j)

Upvotes: 1

running.t
running.t

Reputation: 5709

for w in word: loop is executed outside while line: loop. It means that first you produce single word list for each line and then you skip each such list end executes for w in word: only for last word list.

To fix it change indentation of whoole for w in word: loop (this line and 4 lines below). Move it 4 spaces to the right.

all = []
count = {}
line = input("Enter line: ")
while line:
    print("line is :" + line )
    word = line.split()
    line = input("Enter line: ")
    for w in word:
        if w in count:
            count[w] += 1
        else:
            count[w] = 1
for word in sorted(count):
    print(word, count[word])

It's because indentation in python is used to determine grouping of statements.

Upvotes: 3

Related Questions