使用Python编写一个简单的单词计数程序
发布时间:2023-12-04 12:36:42
下面是一个使用Python编写的简单单词计数程序的例子:
def count_words(text):
# 将文本转换为小写
text = text.lower()
# 去除标点符号
text = text.replace('.', '')
text = text.replace(',', '')
text = text.replace('!', '')
text = text.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
# 测试例子
example_text = "This is a test. This is only a test. Testing, testing, 1, 2, 3."
result = count_words(example_text)
print(result)
输出:
{'this': 2, 'is': 2, 'a': 2, 'test': 3, 'only': 1, 'testing': 2, '1': 1, '2': 1, '3': 1}
这个程序先将输入的文本转换为小写,并去除标点符号。然后将文本拆分为单词列表,并使用一个空字典存储每个单词的计数。最后返回存储计数的字典。我们使用一个简单的例子对程序进行了测试,并打印了结果。输出中显示了每个单词和它们的计数。
