用Python编写一个函数来计算一个字符串中每个单词的出现次数。
发布时间:2023-06-30 04:52:33
以下是一个用Python编写的函数,用于计算一个字符串中每个单词的出现次数:
def count_words(string):
# 将字符串转换为小写,以便不区分大小写
string = string.lower()
# 使用split()方法将字符串分割成单词列表
words = string.split()
# 创建一个空字典来存储每个单词的出现次数
word_count = {}
# 遍历单词列表,对每个单词进行计数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 返回包含每个单词和其出现次数的字典
return word_count
示例用法:
string = "I love Python programming because it is fun and useful. Python is widely used in various fields such as web development, data analysis, and artificial intelligence." result = count_words(string) print(result)
输出结果:
{'i': 1, 'love': 1, 'python': 2, 'programming': 1, 'because': 1, 'it': 1, 'is': 1, 'fun': 1, 'and': 2, 'useful.': 1, 'widely': 1, 'used': 1, 'in': 1, 'various': 1, 'fields': 1, 'such': 1, 'as': 1, 'web': 1, 'development,': 1, 'data': 1, 'analysis,': 1, 'artificial': 1, 'intelligence.': 1}
该函数将字符串转换为小写,并使用split()方法将字符串分割成单词列表。然后,它遍历单词列表,对每个单词进行计数并将结果存储在一个字典中。最后,它返回包含每个单词和其出现次数的字典。
