我正在使用 NLTK 从列表元素中删除停用词。 这是我的代码片段
dict1 = {}
for ctr,row in enumerate(cur.fetchall()):
list1 = [row[0],row[1],row[2],row[3],row[4]]
dict1[row[0]] = list1
print ctr+1,"\n",dict1[row[0]][2]
list2 = [w for w in dict1[row[0]][3] if not w in stopwords.words('english')]
print list2
问题是,这不仅删除了停用词,而且还删除了其他单词中的字符,例如从单词 'orientation' 'i' 和更多停用词将被删除,并且它在 list2 中存储字符而不是单词。 即 ['O', 'r', 'e', 'n', 'n', ' ', 'f', ' ', '3', ' ', 'r', 'e', 'r' , 'e', ' ', 'p', 'n', '\n', '\n', '\n', 'O', 'r', 'e', 'n', 'n' , ' ', 'f', ' ', 'n', ' ', 'r', 'e', 'r', 'e', ' ', 'r', 'p', 'l'.. ...................... 虽然我想将其存储为 ['Orientation','.......................
请您参考如下方法:
首先,确保 list1 是单词列表,而不是字符数组。在这里,我可以为您提供一个代码片段,您或许可以利用它。
from nltk import word_tokenize
from nltk.corpus import stopwords
english_stopwords = stopwords.words('english') # get english stop words
# test document
document = '''A moody child and wildly wise
Pursued the game with joyful eyes
'''
# first tokenize your document to a list of words
words = word_tokenize(document)
print(words)
# the remove all stop words
content = [w for w in words if w.lower() not in english_stopwords]
print(content)
输出将是:
['A', 'moody', 'child', 'and', 'wildly', 'wise', 'Pursued', 'the', 'game', 'with', 'joyful', 'eyes']
['moody', 'child', 'wildly', 'wise', 'Pursued', 'game', 'joyful', 'eyes']
