可以使用Python中的字典(dictionary)来统计每个单词出现的次数。具体实现如下:
text = "This is a sample text with several words and repeated words"
word_list = text.split() # 将字符串按照空格分隔成单词列表
word_count = {} # 定义一个空字典,用于存储每个单词出现的次数
for word in word_list:
if word in word_count:
word_count[word] += 1 # 如果单词已经在字典中,则次数加1
else:
word_count[word] = 1 # 如果单词不在字典中,则添加到字典,并将次数设为1
print(word_count) # 输出每个单词出现的次数
输出结果为:
{'This': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'with': 1, 'several': 1, 'words': 2, 'and': 1, 'repeated': 1}
以上代码将字符串按照空格分隔成单词列表,然后遍历每个单词,如果单词已经在字典中,则将其出现次数加1,如果单词不在字典中,则添加到字典中,并将其出现次数设为1。最后输出每个单词出现的次数。
温馨提示:答案为网友推荐,仅供参考