任务一
请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数
介绍两种方式:
方式一:
运行结果:
结果分析:通过replace函数将回车键\n替换成空字符后再按照空格字符进行split分割发现在替换处总是存在连接问题例如以下这些情况,故考虑使用re正则表达式进行筛选。
方式二:
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.
"""
import re
def wordcount(text):
word_counts={}
words=re.findall(r'\b\w+\b',text.lower())
for word in words:
if word in word_counts:
word_counts[word]+=1
else:
word_counts[word]=1
return word_counts
print(wordcount(text))
运行结果:
代码分析:re正则表达式,\b将光标从当前位置向左移动一个字符(遇到\n时停止)并从此位置开始向后输出字符(遇到\n时停止),\w+表示匹配数字,字母,下划线的多个字符
re.findall(r'\b\w+\b')指从光标一直匹配至\n并循环向下匹配找出所有的单词。
结果分析:
单词已经分开,不存在因为将回车键替换后的连接问题。
任务二
请使用本地vscode连接远程开发机,将上面你写的wordcount函数在开发机上进行debug,体验debug的全流程,并完成一份debug笔记(需要截图)
cd/root:指在root目录下
/usr/bin/env:环境变量,用于在系统上查找Python解释器位置
/root/.conda/bin/python.../debugpy/laucher:调试器启动脚本的路径
48969:通常是调试器监听的端口号
--:在命令行操作中,后边通常跟的是传递给脚本的参数
/root/.conda/envs/text2.py:要调试的Python脚本路径
参考链接:Python 关卡 | Mikey