统计一段英文文本中每个单词出现的次数

🎉摘要:Python 是一门解释型、面向对象、动态类型的高级编程语言,由荷兰程序员 Guido van Rossum 于 1991 年发布,核心设计理念是优雅、明确、简单。

本示例将会实现英文文本清洗、分词、单词去重、次数统计功能,处理大小写、标点符号等常见问题,最后输出统计结果。

示例的处理逻辑如下:

(1)文本预处理

  • lower():把所有单词转为小写,解决大小写不统一问题(如 Hello 和 hello 视为同一个单词)。

  • string.punctuation:包含所有英文标点(!@#$%^&*(),. 等),用 translate() 一次性清除所有标点。

(2)分词

  • split():按空格把清洗后的文本分割成纯单词列表。

(3)计数逻辑

  • 用字典存储结果:键是单词,值是次数。

  • 遍历单词列表,存在则计数 + 1,不存在则初始化为 1。

示例代码:

import string

def count_word_frequency(text):
    """
    统计英文文本中每个单词的出现次数
    :param text: 输入的英文原始文本
    :return: 字典(key=单词,value=出现次数)
    """
    # 1. 文本预处理:转小写 + 去除标点符号
    # 转小写(统一大小写,避免 Hello 和 hello 算两个单词)
    text_lower = text.lower()
    # 去除所有英文标点符号
    translator = str.maketrans('', '', string.punctuation)
    text_clean = text_lower.translate(translator)

    # 2. 分词:按空格分割成单词列表
    words = text_clean.split()

    # 3. 统计单词次数
    word_count = {}
    for word in words:
        if word in word_count:
            # 单词已存在,计数+1
            word_count[word] += 1
        else:
            # 单词不存在,初始化计数为1
            word_count[word] = 1

    return word_count

if __name__ == "__main__":
    # 测试用英文文本
    sample_text = """
    Hello world! Hello Python. Python is fun, fun fun!
    I love Python, and I love coding.
    """

    # 调用函数统计
    result = count_word_frequency(sample_text)

    # 打印结果
    print("单词出现次数统计结果:")
    for word, count in sorted(result.items()):  # sorted() 按字母排序输出
        print(f"{word}: {count} 次")

运行结果:

单词出现次数统计结果:
and: 1 次
coding: 1 次
fun: 3 次
hello: 2 次
i: 2 次
is: 1 次
love: 2 次
python: 3 次
world: 1 次

  



说说我的看法
全部评论(
没有评论
关于
本网站专注于 Java、数据库(MySQL、Oracle)、Linux、软件架构及大数据等多领域技术知识分享。涵盖丰富的原创与精选技术文章,助力技术传播与交流。无论是技术新手渴望入门,还是资深开发者寻求进阶,这里都能为您提供深度见解与实用经验,让复杂编码变得轻松易懂,携手共赴技术提升新高度。如有侵权,请来信告知:hxstrive@outlook.com
其他应用
公众号