在 Python 中查找字符串中每个单词的频率
pythonserver side programmingprogramming
作为文本分析的一部分,我们经常需要对单词进行计数并为它们分配权重,以便在各种算法中进行处理,因此在本文中,我们将了解如何查找给定句子中每个单词的频率。我们可以使用以下三种方法来实现。
使用 Counter
我们可以使用 collections 模块中的 Counter() 来获取单词的频率。在这里,我们首先应用 split() 从行中生成单词,然后应用 most_common()。
示例
from collections import Counter line_text = "Learn and practice and learn to practice" freq = Counter(line_text.split()).most_common() print(freq)
运行上述代码得到以下结果 −
[('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]
使用 FreqDist()
自然语言工具包提供了 FreqDist 函数,该函数显示字符串中的单词数以及不同单词的数量。应用 most_common() 可让我们得到每个单词的频率。
示例
from nltk import FreqDist text = "Learn and practice and learn to practice" words = text.split() fdist1 = FreqDist(words) print(fdist1) print(fdist1.most_common())
运行上述代码得到以下结果 −
<FreqDist with 5 samples and 7 results> [('and', 2), ('practice', 2), ('Learn', 1), ('learn', 1), ('to', 1)]
使用字典
在这种方法中,我们将行中的单词存储在字典中。然后我们应用 count() 来获取每个单词的频率。然后将单词与单词频率值压缩。最终结果显示为字典。
示例
text = "Learn and practice and learn to practice" words = [] words = text.split() wfreq=[words.count(w) for w in words] print(dict(zip(words,wfreq)))
运行上述代码得到以下结果:
{'Learn': 1, 'and': 2, 'practice': 2, 'learn': 1, 'to': 1}