pandas和nltk:得到最常见的短语

时间:2017-07-25 14:57:35

标签: python pandas

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

    dat["text_clean"] = 
    dat["Description"].str.replace('[^\w\s]','').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)

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

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('[^\w\s]','').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)

3 个答案:

答案 0 :(得分:1)

看起来你的BigramCollocationFinder类想要一个单词列表,而不是一个列表列表。试试这个:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

finder = BigramCollocationFinder.from_documents(gg)
相关问题