分离nltk.频率分配单词分成两个列表?

2024-06-30 17:04:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一系列文本是自定义WebText类的实例。每个文本都是一个具有评级(-10到+10)和字数的对象(nltk.频率分配)与之相关的:

>>trainingTexts = [WebText('train1.txt'), WebText('train2.txt'), WebText('train3.txt'), WebText('train4.txt')]
>>trainingTexts[1].rating
10
>>trainingTexts[1].freq_dist
<FreqDist: 'the': 60, ',': 49, 'to': 38, 'is': 34,...>

现在,如何获得两个列表(或字典),其中包含正面评价文本中专用的每个单词(trainingText[].rating>;0),另一个列表包含负面文本中专门使用的每个单词(trainingText[].rating<;0)。让每个列表包含所有正面或负面文本的总字数,这样您就可以得到这样的结果:

^{pr2}$

我考虑过使用集合,因为集合包含唯一的实例,但是我不知道如何使用它nltk.频率分配,除此之外,一个集合不会按词频排序。有什么想法吗?在


Tags: 对象实例文本txt列表单词频率rating
1条回答
网友
1楼 · 发布于 2024-06-30 17:04:55

好吧,假设你从这个开始测试:

class Rated(object): 
  def __init__(self, rating, freq_dist): 
    self.rating = rating
    self.freq_dist = freq_dist

a = Rated(5, nltk.FreqDist('the boy sees the dog'.split()))
b = Rated(8, nltk.FreqDist('the cat sees the mouse'.split()))
c = Rated(-3, nltk.FreqDist('some boy likes nothing'.split()))

trainingTexts = [a,b,c]

那么你的代码应该是:

^{pr2}$

结果是:

>>> only_positive_words
[('the', 4), ('sees', 2), ('dog', 1), ('cat', 1), ('mouse', 1)]
>>> only_negative_words
[('nothing', 1), ('some', 1), ('likes', 1)]

相关问题 更多 >