任务一
请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。
Eg:
Input:
"""Hello world! This is an example. Word count is fun. Is it fun to count words? Yes, it is fun!"""
Output:
{'hello': 1, 'world': 1, 'this': 1, 'is': 4, 'an': 1, 'example': 1, 'word': 1, 'count': 2, 'fun': 3, 'it': 2, 'to': 1, 'words': 1, 'yes': 1}
TIPS:记得先去掉标点符号,然后把每个单词转换成小写。不需要考虑特别多的标点符号,只需要考虑实例输入中存在的就可以。
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. """ def wordcount(text): pass
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.
"""
def wordcount(text):
s=''
for i in text:
if 'a'<=i<='z' or 'A'<=i<='Z' or i==' ':
s+=i
li=s.split()
dict={}
for i in li:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
print(dict)
wordcount(text)
【任务二】
4.1 什么是debug?
当你刚开始学习Python编程时,可能会遇到代码不按预期运行的情况。这时,你就需要用到“debug”了。简单来说,“debug”就是能再程序中设置中断点并支持一行一行地运行代码,观测程序中变量的变化,然后找出并修正代码中的错误。而VSCode提供了一个非常方便的debug工具,可以帮助你更容易地找到和修复错误。
4.2 使用本地Vscode连接InternStudio开发机
4.4 使用Vscode进行Python debug的流程
4.4.1 debug单个python文件
Step1.打开文件夹
在VSCode中打开直接打开root文件夹,或者你想要debug的Python文件所在的文件夹。这里可能会需要再次输入密码。下面我们以打开root文件夹为例。单击Open Folder或者左上角菜单File->Open Folder。
点击运行调试
配置debug
Step4.查看变量
当代码在断点处停下来时,你可以查看和修改变量的值。在“Run and Debug”侧边栏的“Variables”(变量)部分,你可以看到当前作用域内的所有变量及其值。
4.4.2 在vscode使用命令行进行debug
很多时候我们要debug的不止是一个简单的python文件,而是很多参数,参数中不止会有简单的值还可能有错综复杂的文件关系,甚至debug一整个项目。这种情况下,直接使用命令行来发起debug会是一个更好的选择。
4.4.2.1 vscode设置
vscode支持通过remote的方法连接我们在命令行中发起的debug server。首先我们要配置一下debug的config。
还是点击VSCode侧边栏的“Run and Debug”(运行和调试),单击"create a lauch.json file"
配置完以后会打开配置的json文件,但这不是重点,可以关掉。这时我们会看到run and debug界面有变化,出现了debug选项。
4.4.2.2 debug命令行
现在vscode已经准备就绪,让我们来看看如何在命令行中发起debug。如果没有安装debugpy的话可以先通过pip install debugpy安装一下。
python -m debugpy --listen 5678 --wait-for-client ./myscript.py
-
./myscript.py
可以替换为我们想要debug的python文件,后面可以和直接在命令行中启动python一样跟上输入的参数。记得要先在想要debug的python文件打好断点并保存。 -
--wait-for-client
参数会让我们的debug server在等客户端连入后才开始运行debug。在这就是要等到我们在run and debug界面启动debug。
先在终端中发起debug server,然后再去vscode debug页面单击一下绿色箭头开启debug。
点击开始debug
4.4.2.3 使用别名简化命令
这边有个不方便的地方,python -m debugpy --listen 5678 --wait-for-client这个命令太长了,每次都打很麻烦。这里我们可以给这段常用的命令设置一个别名。
在linux
系统中,可以对 ~/.bashrc 文件中添加以下命令
alias pyd='python -m debugpy --wait-for-client --listen 5678'
然后执行
source ~/.bashrc
这样之后使用 pyd 命令(你可以自己命名) 替代 python 就能在命令行中起debug了,之前的debug命令就变成了
pyd ./myscript.py