使用 python3 从列表中删除停用词

Removing stopwords from list using python3

我一直在尝试从使用 python 代码读取的 csv 文件中删除停用词,但我的代码似乎不起作用。我已经尝试在代码中使用示例文本来验证我的代码,但它仍然是一样的。下面是我的代码,如果有人能帮我解决这个问题,我将不胜感激。下面是代码

import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import csv

article = ['The computer code has a little bug' ,
      'im learning python' ,
           'thanks for helping me' ,
            'this is trouble' ,
          'this is a sample sentence'
            'cat in the hat']

tokenized_models = [word_tokenize(str(i)) for i in article]
stopset = set(stopwords.words('english'))
stop_models = [i for i in tokenized_models if str(i).lower() not in stopset]
print('token:'+str(stop_models))

您的 tokenized_models 是标记化句子的列表,因此是列表的列表。因此,以下行尝试将单词列表与停用词匹配:

stop_models = [i for i in tokenized_models if str(i).lower() not in stopset]

相反,再次遍历单词。类似于:

clean_models = []
for m in tokenized_models:
    stop_m = [i for i in m if str(i).lower() not in stopset]
    clean_models.append(stop_m)

print(clean_models)

题外话有用提示:
要定义多行字符串,请使用括号且不要逗号:

article = ('The computer code has a little bug'
           'im learning python'
           'thanks for helping me'
           'this is trouble'
           'this is a sample sentence'
           'cat in the hat')

此版本可以使用您的原始代码

word_tokenize(str(i)) returns 一个单词列表,所以 tokenized_models 是一个列表列表。您需要展平该列表,或者更好的做法是将 article 设为单个字符串,因为我现在不明白为什么它是一个列表。

这是因为 in 运算符不会搜索列表,然后同时搜索该列表中的字符串,例如:

>>> 'a' in 'abc'
True
>>> 'a' in ['abc']
False