python - 从字符串中提取单词以创建特征集 nltk

标签 python nltk

我正在使用 NLTK 和 NLTK-Trainer 进行一些情绪分析。我有一个准确的算法腌制。当我关注 instruction由 NLTK-Trainer 提供,一切正常。

这是有效的(返回所需的输出)

>>> words = ['some', 'words', 'in', 'a', 'sentence']
>>> feats = dict([(word, True) for word in words])
>>> classifier.classify(feats)

'feats' 看起来像这样:

Out[52]: {'a': True, 'in': True, 'sentence': True, 'some': True, 'words': True}

但是,我不想每次都输入以逗号和撇号分隔的单词。我有一个脚本可以对文本进行一些预处理并返回一个如下所示的字符串。

"[['words'], ['in'], ['a'], ['sentence']]"`

但是,当我尝试用字符串定义“feats”时,我得到的结果看起来像这样

{' ': True,
 "'": True,
 ',': True,
 '[': True,
 ']': True,
 'a': True,
 'b': True,
 'c': True,
 'e': True,
 'h': True,
 'i': True,
 'l': True,
 'n': True,
 'o': True,
 'p': True,
 'r': True,
 's': True,
 'u': True}

显然,分类器函数对此输入不是很有效。看起来“feats”定义是从文本字符串中提取单个字母而不是整个单词。 我该如何解决这个问题?

最佳答案

我不确定是否理解,但我建议:

words = nltk.word_tokenize("some words in a sentence")
feats = {word: True for word in words}
classifier.classify(feats)

如果您想使用预处理的文本,请尝试:

text = "[['words'], ['in'], ['a'], ['sentence']]"
words = text[3:len(text)-3].split("'], ['")
feats = {word: True for word in words}
classifier.classify(feats)

关于python - 从字符串中提取单词以创建特征集 nltk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168156/

相关文章:

python - Pandas : Add a column of arrays

python - 将类 A 的实例存储在类 B 的实例中

python - 根据 django 网站上的操作显示用户上个月的进度

python - 停用词删除困境

Python nltk 词干分析器从不删除前缀

python - 如何检查名字和姓氏是否为英文?

python - 如何从列表中制作特征向量

python - 搜索密码中的特殊字符并将这些密码导出到 pandas 数据框

python - 根据某些列中存在的值删除 Pandas 行

python - 创建阿拉伯语语料库