在开发机中创建一个python_taks1.py 文件,填写内容如下:
from collections import Counter
import re
def wordcount(text):
# 使用正则表达式移除标点符号并将文本转换为小写
cleaned_text = re.sub(r'[^\w\s]', '', text).lower()
# 使用Counter来统计单词出现的次数
word_count = Counter(cleaned_text.split())
return dict(word_count)
# 测试代码
if __name__ == "__main__":
text = """Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""
# 调用函数并打印结果
result = wordcount(text)
for word, count in result.items():
print(f"{word}: {count}次")
返回结果
{‘welcome’: 2, ‘50056776’: 1, ‘user’: 1, ‘every’: 1, ‘morning’: 1, ‘the’: 5, ‘sun’: 1, ‘rises’: 1, ‘painting’: 1, ‘sky’: 1, ‘with’: 1, ‘vibrant’: 1, ‘colors’: 1, ‘birds’: 1, ‘sing’: 1, ‘melodies’: 1, ‘greeting’: 1, ‘day’: 1, ‘nature’: 2, ‘s’: 1, ‘beauty’: 1, ‘inspires’: 1, ‘us’: 1, ‘to’: 2, ‘cherish’: 1, ‘life’: 1, ‘and’: 1, ‘seek’: 1, ‘harmony’: 1, ‘amidst’: 1, ‘daily’: 1, ‘chaos’: 1, ‘we’: 1, ‘find’: 1, ‘peace’: 1, ‘in’: 1, ‘rhythm’: 1, ‘of’: 1, ‘shusheng’: 1, ‘llm’: 1, ‘practical’: 1, ‘camp’: 1, ‘course’: 1}
任务二:在开发机上debug wordcount函数:
进行debug调试时使用了Debug扩展,在/root/demo/python_task1.py脚本中导入pdb模块.关于命令的解释如下:
/usr/bin/env: 这是一个环境变量,用于在系统上查找Python解释器的路径。
/root/.miniconda3/bin/python: 这是Python解释器的路径,看起来像是在用户的家目录下的Conda环境中。
/root/.vscode-server/extensions/ms-python.debugpy-2024.0.0-linux-x64/bundled/libs/debugpy/adapter/…/…/debugpy/launcher: 这是debugpy调试器的启动脚本的路径。它位于Visual Studio Code的扩展目录中。
50703: 这通常是调试器监听的端口号。
–: 在命令行参数解析中,–后面跟着的是传递给脚本的参数。
/root/demo/python_task1.py: 这是要调试的Python脚本的路径。
当运行debug以后,UI界面显示如下:
在这里打了断点,我们可以单步执行以下看一下字典word_counts的变化:
当单步执行完一次循环以后我们可以看到,字典中存入了一对键值对,当我们再一次单步执行一边循环,会增加一对新的键值对
这是调试的基本过程,请大佬们指教。