2013-12-23 17 views
5

Ich versuche, eine document classification, as described in NLTK Chapter 6 zu tun, und ich habe Probleme beim Entfernen von Stoppwörtern. Als ichNLTK stopword removal Problem

all_words = (w for w in all_words if w not in nltk.corpus.stopwords.words('english')) 

hinzufügen gibt es

Traceback (most recent call last): 
    File "fiction.py", line 8, in <module> 
    word_features = all_words.keys()[:100] 
AttributeError: 'generator' object has no attribute 'keys' 

Ich vermute, dass die Stoppwort-Code den Typ des Objekts für ‚all_words‘ verwendet, geändert, wodurch sie .key() Funktion nutzlos. Wie kann ich Stoppwörter entfernen, bevor ich die Schlüsselfunktion verwende, ohne den Typ zu ändern? Vollständiger Code unten:

import nltk 
from nltk.corpus import PlaintextCorpusReader 

corpus_root = './nltk_data/corpora/fiction' 
fiction = PlaintextCorpusReader(corpus_root, '.*') 
all_words=nltk.FreqDist(w.lower() for w in fiction.words()) 
all_words = (w for w in all_words if w not in nltk.corpus.stopwords.words('english')) 
word_features = all_words.keys()[:100] 

def document_features(document): # [_document-classify-extractor] 
    document_words = set(document) # [_document-classify-set] 
    features = {} 
    for word in word_features: 
     features['contains(%s)' % word] = (word in document_words) 
    return features 

print document_features(fiction.words('fic/11.txt')) 

Antwort

4

ich dies tun würde, indem sie auf die Vermeidung Zugabe FreqDist Instanz in erster Linie:

all_words=nltk.FreqDist(w.lower() for w in fiction.words() if w.lower() not in nltk.corpus.stopwords.words('english')) 

auf der Größe des Korpus Je ich glaube, Sie wahrscheinlich bekommen würden Leistungssteigerung aus einem Satz für die Stoppwörter zu schaffen, bevor Sie das:

stopword_set = frozenset(ntlk.corpus.stopwords.words('english')) 

Wenn das für Ihre Situation nicht geeignet ist, sieht es aus wie Sie die Vorteile der fa nehmen ct dass FreqDist erbt von dict:

for stopword in nltk.corpus.stopwords.words('english'): 
    if stopword in all_words: 
     del all_words[stopword] 
+0

Perfect. Vielen Dank! – user3128184