如何用Python实现字符串单词按出现次数分组存入字典
实现步骤与完整代码
现有代码问题说明
- 直接
split()拆分得到的单词包含标点(如day.末尾的句号),会导致同一个单词被识别为不同值 - 计数逻辑错误:
count = +1是将变量赋值为1,没有实现累加效果,也没有单独统计每个单词的出现次数 - 缺少「单词计数反向映射为次数对应单词列表」的逻辑
完整实现代码
基础写法(无需引入第三方库)
String = "Today was a very a good day. Tomorrow might be a better day" # 1、清洗单词:去除每个单词附带的标点符号 clean_words = [] for raw_word in String.split(): # 只保留单词中的字母字符,过滤标点 clean_word = ''.join([char for char in raw_word if char.isalpha()]) clean_words.append(clean_word) # 2、统计每个单词的出现次数 word_counter = {} for word in clean_words: if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 # 3、按出现次数分组生成目标字典 res = {} for word, count in word_counter.items(): if count not in res: res[count] = [] res[count].append(word) print(res)
运行后输出结果和你给出的预期完全一致。
简化写法(用Python内置工具)
借助collections.Counter可以简化计数逻辑:
from collections import Counter String = "Today was a very a good day. Tomorrow might be a better day" # 清洗+计数一步完成 clean_words = [''.join([c for c in w if c.isalpha()]) for w in String.split()] word_counter = Counter(clean_words) res = {} for word, cnt in word_counter.items(): # setdefault自动处理键不存在的情况,无需单独判断 res.setdefault(cnt, []).append(word) print(res)
内容的提问来源于stack exchange,提问作者NewbieCoderKid
相关产品推荐
相关产品推荐

