【问题标题】:Stop words nltk/python problem停用词 nltk/python 问题
【发布时间】:2011-07-26 20:41:28
【问题描述】:

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

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()

输出是这样的

[(71, 'allah'), (65, 'ye'), (46, 'day'), (21, 'lord'), (20, 'truth'), (20, 'say'), (20, 'and')

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

【问题讨论】:

    标签: python nltk


    【解决方案1】:

    在制作 word_list2 时尝试剥离你的单词

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

    【讨论】:

    • if not w in ...if w not in ... ?
    • 是的。 (澄清一下:假设您在文本中的某处有“是……并且,否”;那么word_list 将包含yes...and,no.and, 和@987654330即使andno 是,@ 也不会成为停用词。) [这是对拉菲的回应,而不是对 eumiro。 @eumiro,两者都应该工作,我怀疑在性能或清晰度方面有很大差异。]
    • 不幸的是,剥离不会改变任何输出 :( 我怀疑它是错误的停止列表,只是无法弄清楚为什么它不起作用。
    • 试试这个word_list2 = [w.strip() for w in word_list if w.strip() not in nltk.corpus.stopwords.words('english')]
    • 你应该在创建 word_list2 之前在 word_list 上做 punctuation.sub
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2020-04-14
    相关资源
    最近更新 更多