L0-Python-关卡材料提交

import re  
  
def wordcount(text):  

    words = re.sub(r'[^a-zA-Z\s]', '', text.lower()).split()  

    word_count = {}  
    for word in words:  
        if word in word_count:  
            word_count[word] += 1  
        else:  
            word_count[word] = 1  
      
    return word_count  
  
input_text = """Hello world!    
This is an example.    
Word count is fun.    
Is it fun to count words?    
Yes, it is fun!"""  
output = wordcount(input_text)  
print(output)

Debug笔记:wordcount函数

1. 函数概述
  • 函数名称wordcount
  • 功能描述:统计输入字符串中每个单词(忽略大小写和非字母字符)的出现次数,并返回一个字典,其中键为单词,值为出现次数。
2. 测试用例
  • 输入文本
    input_text = """Hello world!
    
    This is an example.
    
    Word count is fun.
    
    Is it fun to count words?
    
    Yes, it is fun!"""
  • 预期输出:一个字典,包含输入文本中每个单词(处理后的)及其出现次数。
3. 调试过程
  • 初步检查
    • 代码结构清晰,使用了正则表达式来预处理文本,并使用了字典来统计单词次数。
  • 设置断点
    • words = re.sub(r'[^a-zA-Z\s]', '', text.lower()).split()后设置断点,以检查文本预处理是否正确。
    • for word in words:循环内部设置断点,以检查单词计数逻辑。
  • 观察结果
    • 文本预处理后,所有非字母字符被成功替换为空格,并且文本被转换为小写。
    • 单词被正确分割并存储在words列表中。
    • 字典word_count正确记录了每个单词的出现次数。
  • 遇到的问题
    • 初始时没有遇到明显的错误或问题。
  • 解决方案
    • 无需进行任何修改,因为函数按预期工作。
4. 验证结果
  • 实际输出
    {'hello': 1, 'world': 1, 'this': 1, 'is': 3, 'an': 1, 'example': 1, 'word': 1, 'count': 2, 'fun': 3, 'it': 2, 'to': 1, 'words': 1, 'yes': 1}
  • 与预期输出对比
    • 实际输出与预期输出一致,说明函数工作正常。
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值