如何用Python统计文本中各单词出现次数?已读单词处理咨询
统计单词出现次数的最佳实践
嘿,这个需求用Python的**字典(dictionary)**来实现简直是天作之合!你之前考虑的数组方案虽然可行,但操作起来繁琐还低效,字典的键值对结构刚好能完美对应“单词-出现次数”的关系,咱们一步步来拆解:
基础实现思路
- 先初始化一个空字典,用来存储每个单词和它的计数
- 遍历文本里的每个单词:
- 如果单词已经在字典里,就把对应计数加1
- 如果是第一次遇到这个单词,就把它加入字典,计数设为1
基础代码示例
# 示例文本 text = "Hello world! Hello Python. Python is great, world is great too." # 先把文本拆分成单词列表(这里简单处理,后面会讲优化) words = text.split() # 初始化计数字典 word_counts = {} for word in words: if word in word_counts: # 单词已存在,计数+1 word_counts[word] += 1 else: # 单词第一次出现,初始化计数为1 word_counts[word] = 1 # 打印统计结果 for word, count in word_counts.items(): print(f"{word}: {count}")
优化:处理大小写和标点
上面的代码会把Hello和hello、world!和world当成不同的单词,咱们可以预处理文本解决这个问题:
import string text = "Hello world! Hello Python. Python is great, world is great too." # 预处理:转小写+去除标点+拆分单词 processed_words = [ word.strip(string.punctuation).lower() for word in text.split() ] word_counts = {} for word in processed_words: word_counts[word] = word_counts.get(word, 0) + 1 # 用get方法更简洁 print(word_counts)
这里用word_counts.get(word, 0)可以省去判断:如果单词不在字典里,get会返回默认值0,加1后刚好是第一次出现的计数。
关于你提到的数组方案
你说的用两个数组(一个存单词、一个存计数)或者多维数组的思路是可行的,但效率很低——每次判断单词是否存在都要遍历整个数组,找索引也很麻烦,比如:
words = [] counts = [] for word in processed_words: if word not in words: words.append(word) counts.append(1) else: index = words.index(word) counts[index] += 1
当文本里的单词数量多起来时,这种方法会明显变慢,所以更推荐用字典。
更简洁的方法:用collections.Counter
Python标准库自带了Counter类,专门用来做计数任务,一行代码就能搞定:
from collections import Counter word_counts = Counter(processed_words) print(word_counts)
它不仅能快速统计,还自带很多实用方法,比如找出现次数最多的单词:word_counts.most_common(3)会返回出现次数前三的单词和计数。
内容的提问来源于stack exchange,提问作者M.K




