【# 第三期实战营闯关任务二 ## Python实现一个wordcount函数 】

在开发机中创建一个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的变化:
在这里插入图片描述
当单步执行完一次循环以后我们可以看到,字典中存入了一对键值对,当我们再一次单步执行一边循环,会增加一对新的键值对
在这里插入图片描述
这是调试的基本过程,请大佬们指教。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值