2016-05-30 21 views
1

私はNLTK Naive Bayes Classifierをフィーチャ抽出機能features_all()で正と負のカテゴリを持つデータセットに実装しようとしています。コードを実行すると、features_all()関数の行にエラーが発生します。ナイーブベイズのためPython NLTK Naive Bayesクラシファイア

コード:

import nltk 
import random 
from nltk.corpus import stopwords 
import nltk.classify.util 
from nltk.corpus.reader import CategorizedPlaintextCorpusReader 
import re 

from feature_extractors import features_all #function for features extraction 

path = "/.../all kom" 

reader = CategorizedPlaintextCorpusReader(path,r'.*\.txt',cat_pattern=r'(^\w..)/*') 

po=reader.sents(categories=['pos']) #tokenize 
ne=reader.sents(categories=['neg']) 

labeled_sentiments = ([(n, 'positive') for n in po] + [(n, 'negative') for n in ne]) 

size = int(len(labeled_sentiments) * 0.9) #for separating training set in 90:10 
random.shuffle(labeled_sentiments) 

featuresets = [(features_all(n), sentiment) for (n, sentiment) in labeled_sentiments] 
train_set = featuresets[:size] 
test_set = featuresets[size:] 

#Naive Bayes 
classifier = nltk.NaiveBayesClassifier.train(train_set) 
#test 
print(classifier.classify(features_all('great'))) 
print(classifier.classify(features_all('bad'))) 
print('Accuracy for Naive Bayes: ',nltk.classify.accuracy(classifier, test_set)) 
print(classifier.show_most_informative_features(15)) 

features_all()関数:

def features_all(dat): 

    f_all_dict=open('all_dict.txt','r',encoding='utf-8').read() 

    f = literal_eval(f_all_dict) 

    result_all = {} 

    for word in f.items(): 
     result_all = {"{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items()} #here is where I get the error 

    if len(f) == len(result_all): 
     return result_all 
    else: 
     return None 

とfeatures_allは、()(例)のような出力が得られます。

great_pos:1, bad_neg:1 

all_dict.txtルックスこのように:

"great":("pos",2),"bad":("neg",2) 

私は、コードを実行すると、それが実行を終了したくないので、私はここで実行を停止しているので、私は、エラーで正確に把握していないので、私はライン result_all = {"{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items()}

上のエラーを取得しますそれが止まる場所なので、私はそれがこの行にあると確信しています。私はちょっと混乱しています。問題が書式設定や関数入力の場合は、もう分かりません。誰かが私が感謝するのを助けることができる場合。

+0

これを試しましたか? '' {} _ {}:{} '。書式(単語、接尾辞、pol * dat.count(word)) ' –

答えて

2

results_allの書式付き返品明細書に"{}_{}:{}".format(word, suffix, pol * dat.count(word)) for word, (suffix, pol) in f.items()を含めるだけで十分です。あなたのコードが動作するかどうかをチェックする非常に簡単な方法は、期待どおりの形式で出力を一貫して取得しているかどうかをチェックすることです。 print("{}_{}".format(word, suffix): pol * dat.count(word) for word, (suffix, pol) in f.items())を単に実行した場合は、無効な構文エラーが表示されます。コードが不明な場合は、印刷文を保管してください!

+0

ありがとう、それは助けました。 –

+0

私は助けになることができてうれしいです。あなたが私の答えが好きならUpvote! :) –

関連する問題