在Python中统计每个词出现的次数有多种实现方法,下面介绍几种常用的技术方案。

使用字典手动统计
可以通过遍历文本中的每个单词,使用字典来记录每个单词的出现次数。如果单词不在字典中,将其作为键加入并设置初始值为;如果已存在,则将其对应的值加。

使用collections.Counter类
Python的collections模块中的Counter类专门用于计数,可以快速统计单词频率。只需将单词列表传递给Counter,它会自动返回每个单词及其出现次数。

正则表达式预处理
对于复杂的文本处理,可以使用正则表达式来清洗文本。通过匹配非字母字符并替换为空格,可以更准确地进行单词分割。

完整实现方案
以下是一个完整的单词频率统计程序,支持从文件读取文本并输出排序结果:


import re
from collections import Counter

def count_words(text):
    """
    统计文本中每个单词的出现次数
    
    Args:
        text (str): 输入的文本内容
    
    Returns:
        list: 按频率降序排列的(单词, 次数)元组列表
    """
    # 将文本转换为小写
    text_lower = text.lower()
    
    # 使用正则表达式匹配单词(包括连字符单词)
    words = re.findall(r'\b[a-z]+(?:-[a-z]+)*\b', text_lower)
    
    # 使用Counter统计词频
    word_counts = Counter(words)
    
    # 按频率降序排序
    sorted_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
    
    return sorted_counts

def count_words_from_file(file_path):
    """
    从文件读取文本并统计词频
    
    Args:
        file_path (str): 文本文件路径
    
    Returns:
        list: 排序后的词频列表
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            text = file.read()
            return count_words(text)
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 未找到")
        return []

def main():
    """
    主函数 - 提供两种使用方式
    """
    print("单词频率统计器")
    print("=" * 30)
    
    # 方式1:直接输入文本
    sample_text = """
    Love is more than a word it says so much.
    When I see these four letters, I almost feel your touch.
    This is only happened since I fell in love with you.
    Why this word does this, I haven't got a clue.
    """
    
    print("示例文本统计结果:")
    result = count_words(sample_text)
    
    # 输出前10个高频词
    print(f"{'单词':<15} {'次数':<8}")
    print("-" * 25)
    for word, count in result[:10]:
        print(f"{word:<15} {count:<8}")
    
    print("\n" + "=" * 30)
    
    # 方式2:从文件统计
    file_path = input("请输入要统计的文件路径(直接回车跳过):")
    if file_path.strip():
        file_result = count_words_from_file(file_path)
        if file_result:
            print(f"\n文件词频统计结果(前20个):")
            print(f"{'单词':<15} {'次数':<8}")
        print("-" * 25)
        for word, count in file_result[:20]:
            print(f"{word:<15} {count:<8}")

if __name__ == "__main__":
    main()
<code_end>

代码功能特点
1. 灵活的输入方式:支持直接输入文本或从文件读取。
2. 智能分词:使用正则表达式准确识别单词边界。
3. 高效统计:利用Counter类实现快速词频统计。
3. 结果排序:自动按词频从高到低排序。
4. 错误处理:包含文件不存在等异常情况的处理。

该程序能够准确统计英语文本中每个单词的出现频率,并以清晰格式输出结果,适用于文本分析和数据处理任务。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐