从字符串中提取单词以创建特征集 nltk
Extract words from string to create featureset nltk
我正在使用 NLTK 和 NLTK-Trainer 进行一些情绪分析。我有一个准确的算法腌制。当我按照 NLTK-Trainer 提供的 instruction 进行操作时,一切正常。
这是有效的(returns 所需的输出)
>>> 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}
但是,我不想每次都输入逗号和撇号分隔的单词。我有一个对文本进行一些预处理的脚本和 returns 一个看起来像这样的字符串。
"[['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)
我正在使用 NLTK 和 NLTK-Trainer 进行一些情绪分析。我有一个准确的算法腌制。当我按照 NLTK-Trainer 提供的 instruction 进行操作时,一切正常。
这是有效的(returns 所需的输出)
>>> 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}
但是,我不想每次都输入逗号和撇号分隔的单词。我有一个对文本进行一些预处理的脚本和 returns 一个看起来像这样的字符串。
"[['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)