我是python新手,需要帮助! 我在练习python NLTK文本分类。 下面是我正在练习的代码示例 http://www.laurentluce.com/posts/twitter-sentiment-analysis-using-python-and-nltk/
我试过这个
from nltk import bigrams
from nltk.probability import ELEProbDist, FreqDist
from nltk import NaiveBayesClassifier
from collections import defaultdict
train_samples = {}
with file ('positive.txt', 'rt') as f:
for line in f.readlines():
train_samples[line]='pos'
with file ('negative.txt', 'rt') as d:
for line in d.readlines():
train_samples[line]='neg'
f=open("test.txt", "r")
test_samples=f.readlines()
def bigramReturner(text):
tweetString = text.lower()
bigramFeatureVector = {}
for item in bigrams(tweetString.split()):
bigramFeatureVector.append(' '.join(item))
return bigramFeatureVector
def get_labeled_features(samples):
word_freqs = {}
for text, label in train_samples.items():
tokens = text.split()
for token in tokens:
if token not in word_freqs:
word_freqs[token] = {'pos': 0, 'neg': 0}
word_freqs[token][label] += 1
return word_freqs
def get_label_probdist(labeled_features):
label_fd = FreqDist()
for item,counts in labeled_features.items():
for label in ['neg','pos']:
if counts[label] > 0:
label_fd.inc(label)
label_probdist = ELEProbDist(label_fd)
return label_probdist
def get_feature_probdist(labeled_features):
feature_freqdist = defaultdict(FreqDist)
feature_values = defaultdict(set)
num_samples = len(train_samples) / 2
for token, counts in labeled_features.items():
for label in ['neg','pos']:
feature_freqdist[label, token].inc(True, count=counts[label])
feature_freqdist[label, token].inc(None, num_samples - counts[label])
feature_values[token].add(None)
feature_values[token].add(True)
for item in feature_freqdist.items():
print item[0],item[1]
feature_probdist = {}
for ((label, fname), freqdist) in feature_freqdist.items():
probdist = ELEProbDist(freqdist, bins=len(feature_values[fname]))
feature_probdist[label,fname] = probdist
return feature_probdist
labeled_features = get_labeled_features(train_samples)
label_probdist = get_label_probdist(labeled_features)
feature_probdist = get_feature_probdist(labeled_features)
classifier = NaiveBayesClassifier(label_probdist, feature_probdist)
for sample in test_samples:
print "%s | %s" % (sample, classifier.classify(bigramReturner(sample)))
但为什么会犯这个错误?
Traceback (most recent call last):
File "C:\python\naive_test.py", line 76, in <module>
print "%s | %s" % (sample, classifier.classify(bigramReturner(sample)))
File "C:\python\naive_test.py", line 23, in bigramReturner
bigramFeatureVector.append(' '.join(item))
AttributeError: 'dict' object has no attribute 'append'
bigram特征向量遵循与unigram特征向量完全相同的原理。因此,就像您提到的教程一样,您必须检查您将使用的任何文档中是否存在bigram特性。
至于bigram特性以及如何提取它们,我已经为它编写了下面的代码。您可以简单地采用它们来更改教程中的变量“tweets”。
你不必打印它们,只需把它们附加到“tweets”列表中就可以了!我希望这能有足够的帮助。否则,如果你还有问题请告诉我。
请注意,在情感分析等应用中,有些研究人员倾向于标记单词并删除标点符号,而有些则不这样做。根据经验,我知道如果不删除标点符号,Naive bayes的工作原理几乎相同,但是支持向量机的准确率会降低。你可能需要反复考虑这些东西,并决定哪些在你的数据集上更有效。
编辑1:
有一本书叫做“用Python进行自然语言处理”,我可以推荐给你。它包含大字图的例子以及一些练习。不过,我认为你甚至可以解决这个案子没有它。选择大词a特征的想法是,我们想知道单词a出现在我们的语料库中的可能性,然后是单词B
单词unigram features是这4个单词中的每一个,而单词bigram features是:
现在你想用这3个作为你的功能。所以下面的代码函数将字符串的所有bigram放入名为
bigramFeatureVector
的列表中。注意,您必须编写自己的
removePunctuation
函数。上面函数的输出是bigram特征向量。您将像您在教程中提到的那样对待unigram特征向量。相关问题 更多 >
编程相关推荐