我正在使用 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/