任务一:python实现wordcount函数
题目:请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。
解题思路:
可以先将标点符号转换成空格,然后按照空格进行单词拆分,将输入的字段全部转换成小写,最后利用python的字典来进行统计。
实现步骤:
创建word_count.py文件
代码片段
import re
def word_count(text):
# 将文本中的所有标点符号替换为空格
cleaned_text = re.sub(r'[^\w\s]', ' ', text)
# 将所有单词转换为小写
cleaned_text = cleaned_text.lower()
# 分割单词
words = cleaned_text.split()
# 创建字典来计数每个单词出现的次数
word_count_dict = {}
for word in words:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
return word_count_dict
# 示例文本
text = """Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""
# 调用函数并打印结果
print(word_count(text))
打印结果:
任务二: Debug记录
1. 将标点替换成空格
2. 将所有字段转换成小写
3. 分割单词
4. 循环计数单词出现的频率