书生大模型实战营学习[2]Python task

学习目标:Python学习

  • Python实现wordcount
  • Vscode连接InternStudio debug笔记

学习内容:

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

input:

"""Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""

output:

{'hello': 1, 'world': 1, 'this': 1, 'is': 4, 'an': 1, 'example': 1, 'word': 1, 'count': 2,
'fun': 3, 'it': 2, 'to': 1, 'words': 1, 'yes': 1}

第一种是使用正则:

import re
from collections import Counter

def wordcount(text):
    # 使用正则表达式将文本中的单词分割开来,同时转换为小写
    words = re.findall(r'\b\w+\b', text.lower())
    # 使用 Counter 来计算每个单词出现的次数
    word_counts = Counter(words)
    return dict(word_counts)

# 输入文本
text = """Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""

# 调用函数并打印结果
print(wordcount(text))

第二种是使用hash

def word_count(text):
    # 创建一个字典来存储单词计数
    hash = {}
    
    # 遍历字符串中的每个字符
    i = 0
    while i < len(text):
        # 检查当前字符是否是字母
        if text[i].isalpha():
            j = i
            word = ''
            # 继续向后查找,直到遇到非字母字符
            while j < len(text) and text[j].isalpha():
                word += text[j].lower()
                j += 1
            # 更新字典中的单词计数
            hash[word] = hash.get(word, 0) + 1
            # 移动索引到单词的末尾
            i = j
        else:
            i += 1
    
    # 返回包含单词计数的字典
    return hash

def main():
    text = """Hello world!  
This is an example.  
Word count is fun.  
Is it fun to count words?  
Yes, it is fun!"""
    word_counts = word_count(text)

    for word, count in word_counts.items():
        print(f"{word}: {count}")

if __name__ == "__main__":
    main()

在这里插入图片描述

任务二:debug

首先输入debug命令行
在这里插入图片描述
运行
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
进入word_count函数
在这里插入图片描述
一步步dubug
填入hash
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值