欢迎访问宙启技术站
智能推送

使用Python编写一个简单的单词统计程序

发布时间:2023-12-04 09:27:51

下面是一个使用Python编写的简单的单词统计程序:

def word_count(text):
    # 将字符串转换为小写,并根据空格拆分为单词列表
    words = text.lower().split()

    # 创建一个字典,用于存储每个单词及其出现的次数
    word_count = {}

    # 遍历单词列表,统计单词出现的次数
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1

    return word_count


# 使用示例
example_text = "This is an example sentence. This sentence is an example."
result = word_count(example_text)

# 输出结果
for word, count in result.items():
    print(f"{word}: {count}")

上述代码中的word_count函数接受一个文本字符串作为参数,并返回一个字典,该字典包含输入文本中每个单词及其出现的次数。我们可以使用该函数统计任何给定文本的单词。

在上述示例中,我们使用了一个简单的测试文本来进行统计。程序会将文本转换为小写,并按照空格拆分为单词列表。然后,它遍历每个单词并更新字典中对应单词的计数器。最后,程序输出每个单词及其出现的次数。

运行上述代码将得到如下输出:

this: 2
is: 2
an: 2
example: 2
sentence.: 1
sentence: 1