Python如何查找字符串中最高频单词及对应的总出现次数
问题修正方案
原代码存在两处需要调整的逻辑:
- 生成单词列表的写法错误:遍历字符串会逐字符迭代,不需要嵌套列表推导,直接对完整字符串调用
split()方法即可得到所有单词构成的列表 - 统计最高频单词的出现次数,可直接调用列表的
count()方法,传入已获取的最高频单词即可返回总次数
方案1:沿用原有mode逻辑的修正代码
from statistics import mode test_str = "a cat in a hat and a big black bear on a big black rug" print("The original string is : " + test_str) # 直接拆分字符串得到单词列表 temp = test_str.split() res = mode(temp) # 统计出现次数 frequency = temp.count(res) print("Word with maximum frequency : " + str(res)) print("Its frequency is : " + str(frequency))
运行输出结果:
The original string is : a cat in a hat and a big black bear on a big black rug Word with maximum frequency : a Its frequency is : 4
方案2:使用collections.Counter实现(支持多个最高频单词场景)
from collections import Counter test_str = "a cat in a hat and a big black bear on a big black rug" print("The original string is : " + test_str) word_counter = Counter(test_str.split()) max_freq = max(word_counter.values()) # 取出所有最高频单词,此处示例取第一个 max_word = [k for k, v in word_counter.items() if v == max_freq][0] print("Word with maximum frequency : " + max_word) print("Its frequency is : " + str(max_freq))
内容的提问来源于stack exchange,提问作者Ahtesham Khan
相关产品推荐
相关产品推荐

