一、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循环;
接下来根据句子的顺序依次进行段落内容的循环,相同出现的单单词进行计数;
最终循环多次,得出最终计数的结果显示,将技术结果进行打印。