欢迎访问宙启技术站
智能推送

Python函数:如何统计字符串中特定单词的出现次数

发布时间:2023-06-30 16:11:38

在Python中,可以使用count()函数来统计字符串中特定单词的出现次数。count()函数接受一个参数,即要统计的子字符串,然后返回该子字符串在原字符串中出现的次数。

以下是一个示例代码,演示如何使用count()函数统计字符串中特定单词的出现次数:

def count_word_occurrences(string, word):
    count = string.count(word)
    return count

string = "This is a sample string. It contains multiple occurrences of the word 'example'. This is an example sentence."

word = "example"
occurrences = count_word_occurrences(string, word)

print(f"The word '{word}' appears {occurrences} times in the string.")

代码输出:

The word 'example' appears 2 times in the string.

在上述代码中,我们定义了一个名为count_word_occurrences()的函数,它接受两个参数:一个字符串和一个要统计的单词。函数内部使用count()函数来统计这个单词在字符串中出现的次数,并将次数赋给变量count。最后,函数返回count的值。

在示例代码中,我们使用了一个字符串变量string,其中包含了多次出现单词"example"的例子句子。我们将要统计的单词赋给变量word,然后调用count_word_occurrences()函数来获取统计结果。最后,使用print()函数输出结果。

通过这种方法,你可以在Python中轻松统计字符串中特定单词的出现次数。请注意,count()函数将对大小写敏感,所以要确保统计的单词与字符串中出现的单词完全匹配。