Python初学者问题词典

2024-05-16 10:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试生成一个具有以下输出的程序:

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

我希望它的工作方式是让你输入几行,当什么都没有提交时,它会计算每行的数量。在

目前,我不能计算一个句子中的每一行,而只能计算整个句子。我的代码:

^{pr2}$

产生输出:

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

而不是第一个

任何帮助都将不胜感激。谢谢


Tags: 代码程序which数量is方式line句子
1条回答
网友
1楼 · 发布于 2024-05-16 10:41:23

代码使用每一行作为字典键,而不是单词。使用^{}拆分行并迭代单词。在

dic = {}

while True:
    line = input('Enter Line: ')
    line = line.lower()    
    if not line:
        break
    for word in line.split():    # <  -
        dic.setdefault(word, 0)  # <  -
        dic[word] += 1           # <  -
for line, n in sorted(dic.items()):
    print(line, n)

顺便说一句,考虑对这种任务使用^{}(计算发生次数)。在

相关问题 更多 >