熊猫和NLTK:获取最常见的短语



python相当新,我正在使用带有一列文本的熊猫数据框。我正在尝试使用该列并使用nltk来查找常用短语(三个或四个单词(。

dat["text_clean"] = 
dat["Description"].str.replace('[^ws]','').str.lower()
dat["text_clean2"] = dat["text_clean"].apply(word_tokenize)
finder = BigramCollocationFinder.from_words(dat["text_clean2"])
finder
# only bigrams that appear 3+ times
finder.apply_freq_filter(3)
# return the 10 n-grams with the highest PMI
print finder.nbest(bigram_measures.pmi, 10)

最初的评论似乎工作正常。但是,当我尝试使用Bigram并置时,它会抛出以下错误。

n [437]: finder = BigramCollocationFinder.from_words(dat["text_clean2"])
finder
Traceback (most recent call last):
File "<ipython-input-437-635c3b3afaf4>", line 1, in <module>
finder = BigramCollocationFinder.from_words(dat["text_clean2"])
File "/Users/abrahammathew/anaconda/lib/python2.7/site-packages/nltk/collocations.py", line 168, in from_words
wfd[w1] += 1
TypeError: unhashable type: 'list'

知道这指的是什么或解决方法。

以下命令也出现相同的错误。

gg = dat["text_clean2"].tolist()    
finder = BigramCollocationFinder.from_words(gg)
finder = BigramCollocationFinder.from_words(dat["text_clean2"].values.reshape(-1, ))

以下内容有效,但返回没有常用短语。

gg = dat["Description"].str.replace('[^ws]','').str.lower()
finder = BigramCollocationFinder.from_words(gg)
finder
# only bigrams that appear 3+ times
finder.apply_freq_filter(2)
# return the 10 n-grams with the highest PMI
print finder.nbest(bigram_measures.pmi, 10)

您的BigramCollocationFinder类似乎想要一个单词列表,而不是列表列表。试试这个:

finder = BigramCollocationFinder.from_words(dat["text_clean2"].values.reshape(-1, ))

您可能需要将列表列表隐藏为元组列表。希望这有效

dat['text_clean2'] = [tuple(x) for x in dat['text_clean2']]
finder = BigramCollocationFinder.from_words(dat["text_clean2"])

CollocationFinder.from_words用于单个文档。您想使用from_documents

finder = BigramCollocationFinder.from_documents(gg)

最新更新