用Python函数来统计文本中某个词汇出现次数
发布时间:2023-07-04 15:51:41
下面给出一个使用Python编写的函数,用于统计文本中某个词汇出现的次数:
def count_word_occurrences(text, word):
count = 0
words = text.split()
for w in words:
if w == word:
count += 1
return count
这个函数接受两个参数:text表示输入的文本字符串,word表示需要统计出现次数的词汇。
函数首先将输入的文本字符串分割成单词列表,使用split()方法来实现。然后,通过遍历单词列表,逐个检查与目标词汇是否匹配。如果匹配,计数变量count就加1。
最后,函数返回统计得到的出现次数。
以下是一个使用示例:
text = "This is a sample text. It contains some repeated words like sample and repeated."
word = "sample"
occurrences = count_word_occurrences(text, word)
print(f"The word '{word}' appears {occurrences} times in the text.")
输出结果为:
The word 'sample' appears 2 times in the text.
这里统计了词汇"sample"在文本中出现的次数。
