任务一
请实现一个wordcount函数,统计英文字符串中每个单词出现的次数,通过构建defaultdict字典,可以避免插入值时需要判断值是否存在
from collections import defaultdict
def word_count(text):
#构建缓存
reval = defaultdict(int)
words = text.strip().split()
for word in words:
# 清洗单词,移除标点符号等
cleaned_word = ''.join(char.lower() for char in word if char.isalnum())
reval[cleaned_word]+=1
return reval
text = """
Got this panda plush toy for my daughter's birthday,
who loves it and takes it everywhere. It's soft and
super cute, and its face has a friendly look. It's
a bit small for what I paid though. I think there
might be other options that are bigger for the
same price. It arrived a day earlier than expected,
so I got to play with it myself before I gave it
to her.
"""
print(word_count(text))
输出结果
任务二
首先是进入函数内,目前缓存中有一个局部变量
首先对文本进行split,
执行完函数后