跳转至

L0 Python 闯关

文档链接

任务概览

任务类型 任务内容 预计耗时
闯关任务 Python实现wordcount 15mins
闯关任务 Vscode连接InternStudio debug笔记 15mins

任务一

请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数。

Eg:

Input:

Python
1
2
3
4
5
"""Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""

Output:

Python
1
2
{'hello': 1,'world!': 1,'this': 1,'is': 3,'an': 1,'example': 1,'word': 1, 
'count': 2,'fun': 1,'Is': 1,'it': 2,'to': 1,'words': 1,'Yes': 1,'fun': 1  }

TIPS:记得先去掉标点符号,然后把每个单词转换成小写。不需要考虑特别多的标点符号,只需要考虑实例输入中存在的就可以。

任务一解答

wordcount.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
from collections import Counter

def wordcount(text: str):
    # 去除标点符号
    text = re.sub(f"[!.,?]", "", text)

    # 转换为小写并分割单词
    words = text.lower().split()

    # 统计单词
    return dict(Counter(words))

print(wordcount(text))

任务二

请使用本地vscode连接远程开发机,将上面你写的wordcount函数在开发机上进行debug,体验debug的全流程,并完成一份debug笔记(需要截图)。

任务二解答

本地vscode用ssh连接远程开发机。

image-20240710154241167

打开 /root/ 目录,创建 l0-python.py 文件,写入任务一解答的内容;此时 VS Code 会提示下载 Python 扩展,下载扩展即可。

image-20240710154441191

下载完扩展后,设置断点,开始调试。

image-20240710155040645

选择 Python Debugger: Debug using launch.json 会在 ~/.vscode/ 目录下生成 launch.json 配置文件,内容如下:

launch.json
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

进入 Python 调试后,用上方的按钮进行 Continue,Step Over 等操作;左侧出现 VARIABLES 视图,显示局部和全局变量。

image-20240710155506162

调试结束,输出结果。

image-20240710155845962

评论