书生普语大模型实战2

一、Python实现wordcount

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

import string

def wordcount(text):
    # 将所有字母转换为小写
    text = text.lower()
    
    # 移除标点符号
    text = text.translate(str.maketrans("", "", string.punctuation))
    
    # 拆分字符串为单词列表
    words = text.split()
    
    # 使用字典统计每个单词出现的次数
    word_freq = {}
    for word in words:
        if word in word_freq:
            word_freq[word] += 1
        else:
            word_freq[word] = 1
            
    return word_freq

# 示例使用
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.
"""

word_count_result = wordcount(text)
print(word_count_result)

思路:

1、首先将大写转化为小写;

2、不需要考虑标点;

3、拆分单词为列表,循环统计单词出现的次数。

运行代码如上,运行结果如下:

二、体验debug的流程

请使用本地vscode连接远程开发机,将上面你写的wordcount函数在开发机上进行debug,体验debug的全流程,并完成一份debug笔记(需要截图)。

1、我先在vscode当中安装python的扩展;

2、开始使用dubug功能逐步调试;

先读取text文档当中内容;

移除了里面的标点

再将字符串拆解成为单词列表

开始执行循环的程序,先从第一个单词got开始,进行if-else循环;

接下来根据句子的顺序依次进行段落内容的循环,相同出现的单单词进行计数;

最终循环多次,得出最终计数的结果显示,将技术结果进行打印。

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值