python - 字计数器(编程导论2(python))

标签 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

拜托,有人可以帮忙吗?

最佳答案

for w in word: 循环在while line: 循环外执行。这意味着首先为每个 line 生成单个 word 列表,然后跳过每个这样的列表 end executes for w in word: only for last 单词 列表。

要修复它,请更改 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 .

关于python - 字计数器(编程导论2(python)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283207/

相关文章:

python - 导入错误 : cannot import name 'ssl' from 'urllib3.util.ssl_'

python - Microsoft Teams - 机器人主程序中的无限循环

来自 psycopg2 PostgreSQL 查询的 Python 数组操作

python - 使用 NCBIXML 仅解析来自 BLAST 输出的前 3 个命中

python - 无法获取 pstats 的输出

python - numpy 掩码数组限制掩码值的频率

python - Pandas-将值设置为空数据框

python - numpy协方差和协方差矩阵通过公式产生不同的结果

python - Python 字典项可以访问同一字典的其他项吗?

python - 使用控制台让 python 在 Windows XP 上以 UTF8 打印