Python单词计数程序:无需字典统计单词出现次数
本程序使用Python语言实现,无需使用字典即可统计输入的英文句子中每个单词出现的次数。
您可以使用字符串的split()方法将输入的英语句子分割成单词列表,然后遍历列表,统计每个单词出现的次数,最后输出结果。
代码如下:
english = input('请输入英语句子:')
words = english.split() # 将句子分割成单词列表
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出结果
for word, count in word_count.items():
print('{}: {}'.format(word, count))
示例输入:
请输入英语句子:I love Python. Python is a powerful language.
输出结果:
I: 1
love: 1
Python.: 1
Python: 1
is: 1
a: 1
powerful: 1
language.: 1
原文地址: https://www.cveoy.top/t/topic/lIko 著作权归作者所有。请勿转载和采集!