自学内容网 自学内容网

Python task

任务1

实现wordcount:
代码如下:

import re
def wordcount(text):
    #全部小写
    text = text.lower()
    text = re.sub(r'[^\w\s]', ' ', text)
    #切分
    words = text.split()

    #计算频率
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1

    return word_count

# Example usage:
input_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.
"""
output = wordcount(input_text)
print(output)

运行结果:
在这里插入图片描述

任务2

在for循环之前打上breakpoint用来开始debug
可以看到字典刚开始是空的
在这里插入图片描述
随着读到单词后如果字典中不存在该key,则添加到字典中
在这里插入图片描述
在这里插入图片描述
当读到第二个it时,由于key已经存在于字典中则将其value改为2
在这里插入图片描述

debug笔记

直接复制到这里了没有截图
debug目的:理解代码中变量的运行轨迹,方便调试代码,快速定位代码中和预想逻辑不同的问题点
作用:
1.简化代码:
将问题隔离,通过逐步删除或修改代码部分来缩小问题范围。
使用简单的测试案例或程序版本来测试假设。

2.使用调试工具:
利用IDE或调试工具,如断点、步进和变量观察,来追踪程序执行过程。
记录和监控程序状态,特别是在错误发生前后的变量值和系统状态。

3.检查常见错误:
检查拼写错误、数据类型不匹配、逻辑错误等常见问题。
验证外部资源和依赖项(如数据库、网络连接等)的配置和状态。


原文地址:https://blog.csdn.net/weixin_45425054/article/details/140643878

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!