Nicht sicher auf der is stopwords
in der Funktion, stelle ich mir es in
sein muss, aber Sie können einen Counterdict mit most_common(10)
verwenden, um den 10 häufigsten zu erhalten:
from collections import Counter
from string import punctuation
def content_text(text):
stopwords = set(nltk.corpus.stopwords.words('english')) # 0(1) lookups
with_stp = Counter()
without_stp = Counter()
with open(text) as f:
for line in f:
spl = line.split()
# update count off all words in the line that are in stopwrods
with_stp.update(w.lower().rstrip(punctuation) for w in spl if w.lower() in stopwords)
# update count off all words in the line that are not in stopwords
without_stp.update(w.lower().rstrip(punctuation) for w in spl if w not in stopwords)
# return a list with top ten most common words from each
return [x for x in with_stp.most_common(10)],[y for y in without_stp.most_common(10)]
wth_stop, wthout_stop = content_text(...)
Wenn Sie in einer nltk Datei sind vorbei Objekt iterieren nur darueber:
def content_text(text):
stopwords = set(nltk.corpus.stopwords.words('english'))
with_stp = Counter()
without_stp = Counter()
for word in text:
# update count off all words in the line that are in stopwords
word = word.lower()
if word in stopwords:
with_stp.update([word])
else:
# update count off all words in the line that are not in stopwords
without_stp.update([word])
# return a list with top ten most common words from each
return [k for k,_ in with_stp.most_common(10)],[y for y,_ in without_stp.most_common(10)]
print(content_text(nltk.corpus.inaugural.words('2009-Obama.txt')))
Die nltk Methode Interpunktion enthält, so dass nicht sein kann, was Sie wollen.
möglich Duplikat [Wie kann ich zählen das Vorkommen eines Listenelements in Python?] (http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) –