NLTK NaiveBayesClassifier input formatting
Question: I am totally stumped with this issue. I am relatively new to python and NLTK.
I am trying to make a naive Bayes classifier and I am not sure if the input
should be a list of tuples, or a dictionary or a list which is a tuple of two
lists.

The following returns an error that `AttributeError: 'str' object has no
attribute 'items'`

    
    
    [('maggie: just a push button. and the electric car uses sensors to drive itself. \n', 'notending')]
    

The format below returns the following error `AttributeError: 'list' object
has no attribute 'items'`

    
    
    [([['the', 'fire', 'chief', 'says', 'someone', 'started', 'the', 'blaze', 'on', 'purpose', 'as', 'a', 'controlled', 'burn', ',', 'but', 'it', 'quickly', 'got', 'out', 'of', 'hand', '.']], 'notending')]
    

And if I use a dictionary, I get the following error `ValueError: too many
values to unpack`

    
    
    {'everyone: bye!': 'ending'}
    

I am calling the naive bayes classifier as `classifier =
nltk.NaiveBayesClassifier.train(d_train)`

I am not sure what is wrong here. Your help is greatly appreciated. Thanks.


Answer: 
    from nltk.classify import NaiveBayesClassifier
    from nltk.corpus import stopwords
    stopset = list(set(stopwords.words('english')))
    
    def word_feats(words):
        return dict([(word, True) for word in words.split() if word not in stopset])
    
    posids = ['I love this sandwich.', 'I feel very good about these beers.']
    negids = ['I hate this sandwich.', 'I feel worst about these beers.']
    pos_feats = [(word_feats(f), 'positive') for f in posids ]
    neg_feats = [(word_feats(f), 'negative') for f in negids ]
    print pos_feats
    print neg_feats
    trainfeats = pos_feats + neg_feats
    classifier = NaiveBayesClassifier.train(trainfeats)
    

Take a look at the positive and negative feats

    
    
    [({'I': True, 'love': True, 'sandwich.': True}, 'positive'), ({'I': True, 'feel': True, 'good': True, 'beers.': True}, 'positive')]
    [({'I': True, 'hate': True, 'sandwich.': True}, 'negative'), ({'I': True, 'feel': True, 'beers.': True, 'worst': True}, 'negative')]
    

So, If you give the sentence 'I hate everything' to classify

    
    
    print classifier.classify(word_feats('I hate everything'))
    

you will get the result as 'negative'.

