Skip to content

【练习】词频统计

项目简介

词频统计

知识模块

  • Python 编程语言

知识点

  • 列表
  • 列表操作
  • 字符串操作
  • 字典
  • 字典操作
  • for-in循环
  • 分支语句-if

受众

  • 初级测试开发工程师
  • 初级Python开发工程师

作业要求

编写一个Python程序,来计算给定文本中每个单词出现的次数。

解题思路

  1. 需要将文本转换为小写,这样在统计时不会因为大小写而产生不一致的结果。使用 .lower() 方法可以实现。

  2. 分割单词: 使用 .split() 方法将文本分割成一个单词列表。

  3. 词频统计字典: 创建一个空字典来存储每个单词的出现次数。遍历单词列表,去除标点符号,然后在字典中更新每个单词的计数。

  4. 循环遍历单词: 使用循环遍历每个单词,可以使用 .strip(".,!?") 方法去除单词中的标点符号,以便准确匹配单词。

  5. 词频统计更新: 检查单词是否已经在字典中。如果是,增加计数;如果不是,在字典中添加该单词并将计数初始化为1。

  6. 输出词频统计结果: 使用 for 循环遍历字典中的键值对,并使用格式化字符串输出每个单词和其出现次数。

完整代码

text = """
Python is a popular programming language. It is widely used for web development, data science, and more.
Python has a simple and readable syntax, which makes it great for beginners.
"""
words = text.lower().split()  # 将文本转换为小写并分割为单词
word_count = {}  # 用于存储单词和出现次数的字典

for word in words:
    word = word.strip(".,!?")  # 去除单词中的标点符号
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1

# 输出词频统计结果
for word, count in word_count.items():
    print(f"{word}: {count}")

代码讲解

  1. words = text.lower().split():这行代码使用 lower() 方法将文本转换为小写形式,然后使用 split() 方法将文本分割为单词列表,并将结果存储在变量 words 中。

  2. word_count = {}:创建一个空字典 word_count,用于存储每个单词以及其出现次数。

  3. ```python
    for word in words:
    word = word.strip(".,!?")  # 去除单词中的标点符号
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
    ```
    - 这是一个循环,遍历 words 列表中的每个单词。
    - 使用 strip(".,!?") 方法去除单词中可能的标点符号,以便准确匹配单词。
    - 使用条件语句判断单词是否已经在 word_count 字典中。如果在字典中,增加计数;如果不在字典中,将单词添加到字典并初始化计数为1。
    
  4. ```python
    for word, count in word_count.items():
        print(f"{word}: {count}")
    ```
    - 用于遍历 word_count 字典中的键值对。
    - 使用格式化字符串输出每个单词和其出现次数。