You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:15:04