字计数器(编程2(python)简介)

时间:2018-07-11 10:31:08

标签: python

我尝试寻找此问题的答案,但没有成功。 (顺便说一句,我15岁,基本上刚开始使用python) 这是我的程序:

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])

这是我得到的答案:

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

我什么时候应该得到:

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

请,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

for w in word:循环在while line:循环之外执行。这意味着首先为每个word生成一个line列表,然后跳过每个这样的列表,最后仅对最后一个for w in word:列表执行word

要解决此问题,请更改whoole for w in word:循环的缩进(此行和下面的4行)。将其向右移动4个空格。

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])

这是因为indentation in python is used to determine grouping of statements

答案 1 :(得分:1)

这是使用Counter模块中的collections的方法,它将给出一个以列表元素作为键的字典,其频率作为值,它可以帮助您减少代码长度和使用for循环,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)