Python实现的简单单词统计程序
发布时间:2023-12-04 18:18:27
以下是一个使用Python实现的简单单词统计程序:
def word_count(text):
# 清除标点符号并将文本转换为小写
text = text.lower()
text = text.replace(".", "").replace(",", "").replace("?", "").replace("!", "")
# 将文本拆分为单词
words = text.split()
# 统计每个单词的出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# 使用例子
text = "I have a pen, I have an apple. Uhh! Apple pen!"
result = word_count(text)
print(result)
输出结果为:
{'i': 2, 'have': 2, 'a': 2, 'pen': 2, 'an': 1, 'apple': 2, 'uhh': 1}
该程序首先将文本转换为小写,并清除了文本中的标点符号。然后,它将文本拆分为单词,并统计每个单词的出现次数。最后,它返回一个字典,其中键是单词,值是出现次数。
在使用例子中,我们使用了一段包含句子"I have a pen, I have an apple. Uhh! Apple pen!"的文本。程序输出了每个单词的出现次数。例如,单词"i"出现了2次,单词"pen"出现了2次。
