Python字典实现词频统计程序无输出问题调试求助
单词计数程序无输出的问题解决
核心错误
你遍历的是空字典myDiction,而不是拆分好的单词列表strLst。空字典里没有任何键,导致整个计数循环根本没执行,最后字典始终为空,自然没有输出。
修正后的代码
把循环对象改成strLst,同时添加标点清理逻辑(避免times,和times被判定为不同单词):
str = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair" # split the str into a list of separate words strL = str.lower() strLst = strL.split() # print(strLst) # create dictionary myDiction = {} # 遍历单词列表而非空字典 for word in strLst: # 清理单词末尾的标点符号 cleaned_word = word.strip(',.?!') if cleaned_word in myDiction: myDiction[cleaned_word] += 1 else: myDiction[cleaned_word] = 1 # print result for key in myDiction: print(key, myDiction[key])
新手调试建议
- 关键步骤打印中间结果:比如取消
print(strLst)的注释,确认拆分后的单词是否符合预期;计数循环中,每次操作后打印myDiction,直观观察字典的变化过程。 - 可以用Python内置工具简化实现:
collections.Counter专门用于计数场景,代码更简洁:
from collections import Counter str = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair" strL = str.lower() # 同时完成拆分和标点清理 strLst = [word.strip(',.?!') for word in strL.split()] counts = Counter(strLst) for key, value in counts.items(): print(key, value)
内容的提问来源于stack exchange,提问作者toothpaste_123
相关产品推荐
相关产品推荐

