Python中如何实现英语单词词频统计?

我不会编程,但是最近在准备考试,想要统计下这个词频,遇到的问题是:单词的原形和单词的变形怎么统一统计成单词原形,有个哥们在知乎上写了代码,但不懂,运行起来出了问题,代码链接在这里,https://github.com/Enaunimes/freeq,知乎原问题链接在这里,https://www.zhihu.com/question/20632675/answer/100615805,有哪位哥哥帮我看下啊,谢谢了。
Python中如何实现英语单词词频统计?


3 回复
import re
from collections import Counter

def count_word_frequency(text):
    """
    统计英文文本中单词的出现频率
    
    参数:
        text: 输入的英文文本字符串
    
    返回:
        按频率降序排列的单词频率列表,每个元素为(单词, 次数)元组
    """
    # 1. 转换为小写并移除标点符号
    text = text.lower()
    words = re.findall(r'\b[a-z]+\b', text)  # 匹配纯英文单词
    
    # 2. 使用Counter统计词频
    word_counts = Counter(words)
    
    # 3. 按频率降序排序
    sorted_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
    
    return sorted_counts

# 使用示例
if __name__ == "__main__":
    sample_text = """
    Hello world! This is a test. Hello again, world.
    Python is great for text processing. Python, python, PYTHON!
    """
    
    frequencies = count_word_frequency(sample_text)
    
    # 打印前10个高频词
    print("单词频率统计结果:")
    print("-" * 25)
    for word, count in frequencies[:10]:
        print(f"{word:15} : {count:3}次")
    
    # 也可以获取全部结果
    print(f"\n总共找到 {len(frequencies)} 个不同的单词")

代码说明:

  1. 文本预处理text.lower()将所有字母转为小写,确保"Python"和"python"被识别为同一个单词。re.findall(r'\b[a-z]+\b', text)使用正则表达式提取纯英文单词,排除数字和标点。

  2. 词频统计Counter来自collections模块,是专门为计数设计的字典子类,比手动循环统计更高效。

  3. 结果排序sorted()按词频降序排列,key=lambda x: x[1]指定按计数值排序。

扩展建议:

  • 如需排除常见停用词(如"the", “is”, “a”),可创建停用词列表进行过滤
  • 处理大文件时建议逐行读取,避免内存不足
  • 可添加strip()去除文本首尾空白字符

一句话总结:Counter加正则提取是最简洁高效的词频统计方案。


我猜你可以用 NLTK https://www.nltk.org/ 做词形还原,一个简单的例子: https://pythonprogramming.net/lemmatizing-nltk-tutorial/

谢谢~,你们英语真好。。

回到顶部