Python Pandas NLTK Извлекает общие фразы (нграммы) из текстового поля в Dataframe «Аргумент join ()» Ошибка - PullRequest
0 голосов
/ 30 ноября 2018

У меня есть следующий пример фрейма данных:

No  category    problem_definition_stopwords
175 2521       ['coffee', 'maker', 'brewing', 'properly', '2', '420', '420', '420']
211 1438       ['galley', 'work', 'table', 'stuck']
912 2698       ['cloth', 'stuck']
572 2521       ['stuck', 'coffee']

Поле 'problem_definition_stopwords' уже размечено с удаленными словами пробела.

Я хочу создать n-граммы из 'Поле problem_definition_stopwords.В частности, я хочу извлечь n-грамм из моих данных и найти те, которые имеют самую высокую точную взаимную информацию (PMI).

По сути, я хочу найти слова, которые встречаются вместе гораздо больше, чем я ожидал бы их случайно.

Я попробовал следующий код:

import nltk
from nltk.collocations import *

bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()

# errored out here 
finder = BigramCollocationFinder.from_words(nltk.corpus.genesis.words(df['problem_definition_stopwords']))

# only bigrams that appear 3+ times
finder.apply_freq_filter(3) 

# return the 10 n-grams with the highest PMI
finder.nbest(bigram_measures.pmi, 10) 

Полученная ошибка была на третьем фрагменте кода ... TypeError: аргумент join () должен быть str или байтами, а не 'list'

Редактировать: более переносимый формат для DataFrame:

>>> df.columns
Index(['No', 'category', 'problem_definition_stopwords'], dtype='object')
>>> df.to_dict()
{'No': {0: 175, 1: 211, 2: 912, 3: 572}, 'category': {0: 2521, 1: 1438, 2: 2698, 3: 2521}, 'problem_definition_stopwords': {0: ['coffee', 'maker', 'brewing', 'properly', '2', '420', '420', '420'], 1: ['galley', 'work', 'table', 'stuck'], 2: ['cloth', 'stuck'], 3: ['stuck', 'coffee']}}

1 Ответ

0 голосов
/ 30 ноября 2018

Не похоже, что вы правильно используете from_words, глядя на help(nltk.corpus.genesis.words)

Help on method words in module nltk.corpus.reader.plaintext:

words(fileids=None) method of nltk.corpus.reader.plaintext.PlaintextCorpusReader instance
    :return: the given file(s) as a list of words
        and punctuation symbols.
    :rtype: list(str)
(END)

Это то, что вы ищете?Поскольку вы уже представляли свои документы в виде списков строк, что, по моему опыту, прекрасно работает с NLTK, я думаю, вы можете использовать метод from_documents:

finder = BigramCollocationFinder.from_documents(
    df['problem_definition_stopwords']
)

# only bigrams that appear 3+ times
# Note, I limited this to 1 since the corpus you provided
# is very small and it'll be tough to find repeat ngrams
finder.apply_freq_filter(1) 

# return the 10 n-grams with the highest PMI
finder.nbest(bigram_measures.pmi, 10) 

[('brewing', 'properly'), ('galley', 'work'), ('maker', 'brewing'), ('properly', '2'), ('work', 'table'), ('coffee', 'maker'), ('2', '420'), ('cloth', 'stuck'), ('table', 'stuck'), ('420', '420')]
...