0

I am quite new to python. I have read all data from csv file using

import csv
import nltk

f = open('C:/Users/Documents/Data/exp.csv')
csv_f = csv.reader(f)

dataset = []

for row in csv_f:
    dataset.append(row)

print (dataset)

Now, I want to do nltk.NaiveBayesClassifier How can I do that?

The Madman
  • 41
  • 8
  • 1
    Have you read [this](http://www.nltk.org/book/ch06.html)? it has an example on how to use `NaiveBayesClassifier` – Francisco Nov 04 '16 at 06:54
  • 1
    You could find your answer with some examples here: [link](http://stackoverflow.com/questions/20827741/nltk-naivebayesclassifier-training-for-sentiment-analysis) – maanijou Nov 04 '16 at 07:09

1 Answers1

1

For example, if the content of the CSV is the following:

CSV

Size,Color,Shape,Accept
small,blue,oval,yes
small,green,oval,yes
big,green,oval,no
big,red,square,no
small,red,square,no
small,blue,square,yes
big,red,circle,yes

And we want to know whether a small-red-oval item will be accepted using the nltk Naive Bayes, we can use the following code:

python

import csv
import nltk

f = open('C:/Users/Amrit/Documents/Data/exp.csv')
csv_f = csv.reader(f)
csv_f.next()  #skip the header line

dataset = []

for row in csv_f:
    dataset.append(({'size': row[0], 'color': row[1], 'shape': row[2]}, row[3]))

print (dataset)

classifier = nltk.NaiveBayesClassifier.train(dataset)

mydata = {'size':'small', 'color':'red', 'shape':'oval'}
print (mydata, classifier.classify(mydata))

Note: I'm also learning. Thanks to links provided by @Franscisco Couzo and @Milad M

elfan
  • 1,131
  • 6
  • 11