python怎么统计字符串中单词出现的次数

   2025-02-13 2340
核心提示:要统计字符串中单词出现的次数,可以使用Python的内置功能和字符串方法来实现。以下是一种实现方式:def count_words(string):#

要统计字符串中单词出现的次数,可以使用Python的内置功能和字符串方法来实现。以下是一种实现方式:

def count_words(string):    # 将字符串转换为小写,并去除标点符号    string = string.lower().replace(",", "").replace(".", "").replace("!", "").replace("?", "")    # 将字符串分割成单词列表    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 am a student. I am studying computer science."word_count = count_words(string)print(word_count)

输出结果为:

{'i': 2, 'am': 2, 'a': 1, 'student': 1, 'studying': 1, 'computer': 1, 'science': 1}

这段代码首先将字符串转换为小写,并去除标点符号。然后,将字符串分割成单词列表。接下来,创建一个空字典来存储单词出现的次数。然后,遍历单词列表,并统计每个单词出现的次数,将结果存储在字典中。最后,返回单词出现的次数字典。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言