Python
Python实现wordcount
import string
def wordcount(text):
# 去除标点符号
translator = str.maketrans('', '', string.punctuation)
text = text.translate(translator)
# 将所有单词转换为小写
text = text.lower()
# 将文本分割为单词列表
words = text.split()
# 统计每个单词出现的次数
ans={}
for word in words:
if word not in ans:
ans[word] = 1
else:
ans[word] += 1
return ans
text = """Hello world!
This is an example.
Word count is fun.
Is it fun to count words?
Yes, it is fun!"""
res = wordcount(text)
print(res)
结果
{'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}
Vscode连接InternStudio debug笔记
-
初始状态
-
去除符号
-
转换小写
-
统计词数