从字符串中提取单词以创建featureset nltk

时间:2015-07-01 17:41:40

标签: python nltk

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

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

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

'技艺'看起来像这样:

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

但是,我不想每次都输入用逗号和撇号分隔的单词。我有一个脚本对文本进行一些预处理,并返回一个看起来像这样的字符串。

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

然而,当我尝试定义“壮举”时,对于字符串,我留下了一些看起来像这样的东西

{' ': 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}

显然,分类器功能对此输入非常有效。这看起来像是'#feat;'定义是从文本字符串中提取单个字母而不是整个单词。 如何解决此问题?

1 个答案:

答案 0 :(得分:1)

我不确定,但我会建议:

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)