如何修复Python字符频率统计程序查询字母出现次数的报错
存在的问题
- 核心报错:你使用了未定义的
count()函数,字符频率已经存储在newDic字典中,直接通过键newLetter取值即可,不需要额外调用不存在的count方法。 - 输出格式不匹配:打印结果缺少要求的前缀文本,还存在拼写错误
Dictinary(应为Dictionary)。 - 命名不规范:使用Python内置类型名
dict作为自定义变量名,存在冲突风险。
修改后的完整代码
strEntry = str(input("Enter a string: ").upper()) strEntry = strEntry.replace(",", "") strEntry = strEntry.replace(" ", "") print('') def freq_finder(strFinder): freq_dict = {} for i in strFinder: keys = freq_dict.keys() if i in keys: freq_dict[i] += 1 else: freq_dict[i] = 1 return freq_dict newDic = freq_finder(strEntry) print("Dictionary: ", newDic) newLetter = str(input("Choose a letter: ").upper()) if newLetter in newDic: print("Frequency count of that letter:", newDic[newLetter]) newDic.pop(newLetter) print("Dictionary after that letter removed:", newDic) else: print("Letter not in dictionary") sortedDic = sorted(newDic) print("Letters sorted:", sortedDic)
修改说明
- 把报错行的
count(newLetter)替换为newDic[newLetter],直接从频率字典读取对应字母的统计值,解决运行报错。 - 为所有打印结果添加了和预期效果一致的前缀文本,修正了Dictionary的拼写错误。
- 将函数内部的
dict变量名改为freq_dict,避免和Python内置的字典类型名冲突。 - 原有逻辑完全保留,不存在的字母仍会正常给出提示。
内容的提问来源于stack exchange,提问作者MBahreman
相关产品推荐
相关产品推荐

