任务概览
任务一:Python实现wordcount函数
题目
代码
import re
from collections import Counter
def wordcount(text):
# 转换为小写
text = text.lower()
# 移除标点符号
words = re.findall(r"\b[\w']+\b", text)
# 分割成单词列表
words = text.split()
# 计算每个单词出现的次数
return Counter(words)
if __name__ == '__main__':
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.
"""
result = wordcount(text)
print(wordcount(text))
print(wordcount(text))
结果
任务二:远程debug
打断点
打如下断点,目的是观察再执行至断点时变量的情况,再观察执行断点处代码后变量的变化情况。
开始debug
点击运行并调试
可以观察到程序执行是先从“main”作为程序的入口,然后执行到后面的代码,可以观察到这时候程序还没有执行wordcount函数,我们可以看到text变量,其中“\n”代表换行符。
点击继续,我们可以看到我们进入函数体内部了,具体我们可以看调用堆栈,调用函数实际用到了栈这个数据结构,利用了栈的先进后出特性。此时我们看到这个栈里的变量相较于之前在__main__函数里少了额外的变量。
继续执行,可以看到字符串的字符全部变为小写。
再继续执行,发现字符串里的标点符号全部去除(注意一个细节,daughter’s单词不能去掉单引号,不然会变为daughters,因此在正则化代码进行特殊的处理)。
再继续执行,wordcount函数执行完毕,返回值
心得
debug其实是帮助我们观察变量的变化情况,如果执行断点处代码后变量和我们设想结果不一样,就可以断定断点处代码出了问题。