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

使用Python统计文本中某个单词出现次数的函数

发布时间:2023-07-02 07:30:25

要统计文本中某个单词出现的次数,可以定义一个函数,接受两个参数:文本字符串和要统计的单词。函数首先将文本字符串转换为小写,然后使用split()方法将文本字符串分割成单词列表。

接下来,我们可以使用count()方法统计给定单词在文本中出现的次数,并将结果返回。

下面是一个基本的实现例子:

def count_word(text, word):
    text = text.lower()
    word_list = text.split()
    count = word_list.count(word)
    return count

接下来,我们可以测试这个函数:

text = "Python is a powerful programming language. Python is used for web development, data analysis, machine learning, and more."
word = "Python"

count = count_word(text, word)
print(f"The word '{word}' appears {count} times in the text.")

这样,count_word()函数就能统计给定单词在文本中出现的次数,并将结果打印出来。

另外,这个函数只会统计完全匹配的单词,不会统计单词的部分出现。如果要统计部分匹配的次数,可以使用正则表达式模块re来实现。下面是一个示例:

import re

def count_word_regex(text, word):
    text = text.lower()
    count = len(re.findall(r"\b" + re.escape(word) + r"\b", text))
    return count

这个函数使用re.findall()方法找到所有与给定单词完全匹配的单词,并返回匹配到的次数。注意,需要使用re.escape()方法对给定单词进行转义,以便正则表达式能够正确匹配。

同样,我们可以进行测试:

text = "Python is a powerful programming language. Python is used for web development, data analysis, machine learning, and more."
word = "Python"

count = count_word_regex(text, word)
print(f"The word '{word}' appears {count} times in the text.")

这样,count_word_regex()函数就能统计给定单词在文本中出现的次数,并将结果打印出来。

这两个函数都可以统计文本中给定单词的出现次数,可以根据实际需求选择使用哪个函数。