【书生大模型实战营】python笔记

68 阅读2分钟

请实现一个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}

TIPS:记得先去掉标点符号,然后把每个单词转换成小写。不需要考虑特别多的标点符号,只需要考虑实例输入中存在的就可以。

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.
"""

def wordcount(text):
    pass

python对字符串有很多方法。针对这题,可以想到先把标点符号换成空格,再利用split()分割空格,这样得到所有单词的列表。根据列表在字符串里一个个找出现次数。

有个小问题,给的字符串里存在缩写:It‘s,也存在不是缩写daughter’s。因为题目说只针对该字符串,所以单独考虑一下就好。

替换用replace()函数。有换行符也要注意替换成空格。

image.png

image.png 远程连接后,安装插件

image.png 开始远程debug。这是一开始。

image.png 单步调试一行一行的走

image.png 这是完成替换标点、换行符、缩写、小写之后的text

image.png

继续直接到下一个断点的位置,在这里就算第一个重复单词it出现的时候

image.png 单步跳出直接结束函数了

image.png 逐过程没进入函数了。

image.png 命令行发起debug也成功了

image.png