Python中单词频率统计函数实现
发布时间:2023-06-22 19:54:49
Python是一门非常强大的编程语言,它在数据处理和统计分析领域有着广泛的应用。在这篇文章中,我们将介绍一种Python函数,用于统计一个字符串中单词出现的频率。
在Python中实现单词频率统计的方法有很多种,我们将使用最基本的方法。假如我们有一个字符串,需要统计其中每个单词出现的次数。首先,我们需要将这个字符串转换为单词列表。
def word_count(string): words = string.split() # 将字符串分割成单词列表 return words
这个函数使用了split()方法,将字符串按照空格分割成了一个单词列表。现在,我们可以尝试使用这个函数。
string = "hello world, this is a test string. hello world!" words = word_count(string) print(words)
输出结果:
['hello', 'world,', 'this', 'is', 'a', 'test', 'string.', 'hello', 'world!']
现在我们已经得到了一个单词列表,下一步需要统计每个单词出现的次数。我们可以使用Python中的字典数据结构来存储单词以及对应的出现次数。
def word_count(string):
words = string.split()
word_count_dict = {}
for word in words:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
return word_count_dict
这个函数使用了for循环遍历单词列表,如果一个单词在字典中已经存在,就将其对应的值加1,否则将其添加到字典中,并将其值设置为1。现在,我们可以试试这个函数。
string = "hello world, this is a test string. hello world!" word_counts = word_count(string) print(word_counts)
这个函数的输出结果为:
{'hello': 2, 'world,': 1, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'string.': 1, 'world!': 1}
我们可以看到,这个函数成功地统计了字符串中的单词频率,并将其保存在了一个字典中。
以上就是Python中实现单词频率统计的基本方法。如果你需要更加高级的功能,如去除停用词等,可以使用第三方库。常用的第三方库包括NLTK和Scikit-learn,它们提供了更加强大的文本处理和机器学习算法。
