通过`collections.Counter`统计一篇英文文章中每个单词的出现频率,同时忽略大小写和标点符号。

from collections import Counter
import re

def count_word_frequencies(text):
    # 使用正则表达式匹配单词,忽略大小写和标点符号
    words = re.findall(r'\b\w+\b', text.lower())
    # 使用Counter统计单词频率
    word_counts = Counter(words)
    return word_counts

# 示例文本
example_text = """
Hello, world! This is a test. Hello again, world. This is only a test.
"""

# 调用函数并打印结果
word_frequencies = count_word_frequencies(example_text)
for word, count in word_frequencies.items():
    print(f"{word}: {count}")

解释

  1. 导入模块:collections.Counter 用于统计频率,re 用于正则表达式匹配。
  2. 正则匹配:re.findall(r'\b\w+\b', text.lower()) 中的 \b\w+\b 匹配完整的单词,text.lower() 将所有字符转换为小写,从而忽略大小写。
  3. 统计频率:Counter(words) 直接统计列表中每个单词的出现次数。
  4. 示例输出:调用函数后,遍历 word_frequencies 并打印每个单词及其出现次数。
  5. 输出结果:示例文本中,hello 和 world 各出现2次,this、is、a、test 各出现2次,only 出现1次。

详细说明

  • 正则表达式:\b 表示单词边界,\w+ 匹配一个或多个字母或数字。text.lower() 确保大小写统一。
  • Counter 特性:Counter 是字典的子类,直接统计可迭代对象的元素频率,支持排序和常见操作。
  • 扩展性:可以进一步过滤停用词或添加词干提取功能。

示例代码运行结果

hello: 2
world: 2
this: 2
is: 2
a: 2
test: 2
only: 1

注意事项

  • 标点符号处理:正则表达式已经排除标点符号。
  • 性能优化:对于大文本,Counter 是高效的选择。
  • 局限性:未处理复数形式(如 tests 和 test 被视为不同单词),如需解决需额外逻辑。

通过以上方法,可以高效地统计英文文章中每个单词的频率,同时满足忽略大小写和标点符号的要求。