Python Pandas NLTK 从 Dataframe 'join() argument' 错误的文本字段中提取常用短语 (ngrams)

标签 python pandas nltk phrase trigram

我有以下示例数据框:

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' 字段已经被标记化,删除了停用词。

我想从“problem_definition_stopwords”字段创建 n-gram。具体来说,我想从我的数据中提取 n-gram 并找到具有最高点智能互信息 (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 或 bytes,而不是 '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']}}

最佳答案

您似乎没有使用 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')]

关于Python Pandas NLTK 从 Dataframe 'join() argument' 错误的文本字段中提取常用短语 (ngrams),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53560439/

相关文章:

python - 使用 matplotlib 和 opencv2 在图像上绘图,更新图像?

python - '\a'如何在python中等于 '\7'?

python - 将 Pelican 文章拆分为多个页面

python - 无法将 xgboost 添加到 pyinstaller

python - 未找到朋克

python - Jupyter Notebook 中的 SQL 列类型

python - 用条件填充列

python - 从 pandas 的数据框列中搜索字符串模式

python - Jython:导入错误:没有名为 multiarray 的模块

python - 如何计算未出现在WordNet中的英文单词的相似度?