在Python中查找字符串中每个单词的频率


作为文本分析的一部分,我们经常需要统计单词并为它们分配权重,以便在各种算法中进行处理。因此,在本文中,我们将了解如何找到给定句子中每个单词的频率。我们可以通过以下三种方法实现。

使用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 outcomes>
[('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}

更新于:2019年12月20日

10K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.