【问题标题】:Removing stopwords from list using python3使用python3从列表中删除停用词
【发布时间】:2016-09-25 01:18:54
【问题描述】:

我一直在尝试从我使用 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))

【问题讨论】:

  • 作为一般建议,简单地打印出当前行之间的值以查看发送到每个后续行的内容很有用。
  • 谢谢,我试过了,没有任何运气!!

标签: python python-3.x nltk stop-words


【解决方案1】:

您的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')

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 2018-09-28
      • 2021-12-22
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多