10

我是 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'
4

1 回答 1

16

二元组特征向量遵循与一元组特征向量完全相同的原则。因此,就像您提到的教程一样,您必须检查您将使用的任何文档中是否存在二元组特征。

至于二元特征以及如何提取它们,我已经为它编写了下面的代码。您可以简单地采用它们来更改教程中的变量“tweets”。

import nltk
text = "Hi, I want to get the bigram list of this string"
for item in nltk.bigrams (text.split()): print ' '.join(item)

您可以简单地将它们附加到“推文”列表中,而不是打印它们,您就可以开始了!我希望这会足够有帮助。否则,如果您还有问题,请告诉我。

请注意,在情感分析等应用程序中,一些研究人员倾向于对单词进行标记并删除标点符号,而另一些则不这样做。根据经验,我知道如果不删除标点符号,朴素贝叶斯的工作原理几乎相同,但是 SVM 的准确率会降低。您可能需要玩弄这些东西并决定哪些对您的数据集更有效。

编辑1:

有一本书叫《Natural language processing with Python》,我可以推荐给你。它包含二元组的示例以及一些练习。但是,我认为你甚至可以在没有它的情况下解决这个问题。选择二元组特征背后的想法是我们想知道单词 A 在我们的语料库中出现在单词 B 之后的概率。因此,例如在句子中

“我开卡车”

单词unigram features将是这4个单词中的每一个,而单词bigram features将是:

[“我开车”、“开一辆”、“一辆卡车”]

现在您想使用这 3 个作为您的功能。因此,下面的代码函数将字符串的所有二元组放入名为 的列表中bigramFeatureVector

def bigramReturner (tweetString):
  tweetString = tweetString.lower()
  tweetString = removePunctuation (tweetString)
  bigramFeatureVector = []
  for item in nltk.bigrams(tweetString.split()):
      bigramFeatureVector.append(' '.join(item))
  return bigramFeatureVector

请注意,您必须编写自己的removePunctuation函数。作为上述函数的输出,您得到的是二元特征向量。您将完全按照您提到的教程中处理一元特征向量的方式来处理它。

于 2012-12-24T21:56:23.290 回答