停用词nltk / python问题

Ale*_*lex 5 python nltk

我有一些处理数据集供以后使用的代码,我用于停用词的代码似乎还可以,但是我认为问题出在我代码的其余部分,因为它似乎只删除了一些停用词。

import re
import nltk

# Quran subset
filename = 'subsetQuran.txt'

# create list of lower case words
word_list = re.split('\s+', file(filename).read().lower())
print 'Words in text:', len(word_list)

word_list2 = [w for w in word_list if not w in nltk.corpus.stopwords.words('english')]



# create dictionary of word:frequency pairs
freq_dic = {}
# punctuation and numbers to be removed
punctuation = re.compile(r'[-.?!,":;()|0-9]') 
for word in word_list2:
    # remove punctuation marks
    word = punctuation.sub("", word)
    # form dictionary
    try: 
        freq_dic[word] += 1
    except: 
        freq_dic[word] = 1


print '-'*30

print "sorted by highest frequency first:"
# create list of (val, key) tuple pairs
freq_list2 = [(val, key) for key, val in freq_dic.items()]
# sort by val or frequency
freq_list2.sort(reverse=True)
freq_list3 = list(freq_list2)
# display result
for freq, word in freq_list2:
    print word, freq
f = open("wordfreq.txt", "w")
f.write( str(freq_list3) )
f.close()
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样

[(71, 'allah'), (65, 'ye'), (46, 'day'), (21, 'lord'), (20, 'truth'), (20, 'say'), (20, 'and')
Run Code Online (Sandbox Code Playgroud)

这只是一个小样本,应该删除其他样本。任何帮助表示赞赏。

Raf*_*afi 4

尝试在制作 word_list2 时删除您的单词

word_list2 = [w.strip() for w in word_list if w.strip() not in nltk.corpus.stopwords.words('english')]
Run Code Online (Sandbox Code Playgroud)