【问题标题】:removing stop words and string.punctuation删除停用词和 string.punctuation
【发布时间】:2017-08-04 22:15:20
【问题描述】:

我不明白为什么这不起作用:

import nltk
from nltk.corpus import stopwords
import string

with open('moby.txt', 'r') as f:
    moby_raw = f.read()
    stop = set(stopwords.words('english'))
    moby_tokens = nltk.word_tokenize(moby_raw)
    text_no_stop_words_punct = [t for t in moby_tokens if t not in stop or t not in string.punctuation]

    print(text_no_stop_words_punct)

查看输出我有这个:

[...';', 'surging', 'from', 'side', 'to', 'side', ';', 'spasmodically', 'dilating', 'and', 'contracting',...]

标点符号似乎还在。我做错了什么?

【问题讨论】:

    标签: python nltk punctuation


    【解决方案1】:

    必须是and,而不是or

    if t not in stop and t not in string.punctuation
    

    或者:

    if not (t in stop or t in string.punctuation):
    

    或者:

    all_stops = stop | set(string.punctuation)
    if t not in all_stops:
    

    后一种方案最快。

    【讨论】:

      【解决方案2】:

      在这一行更改中,尝试将“或”更改为“和”,这样您的列表将只返回既不是停用词又不是标点符号的词。

      text_no_stop_words = [t for t in moby_tokens if t not in stop or t not in string.punctuation]
      

      【讨论】:

        【解决方案3】:

        关闭。 您需要在比较中使用and 而不是or。 如果结果是像“;”这样的标点符号不在stop 中,那么python 不会检查它是否在string.punctuation 中。

        text_no_stop_words_punct = [t for t in moby_tokens if t not in stop and t not in string.punctuation]
        

        【讨论】:

          猜你喜欢
          • 2020-08-19
          • 2016-05-21
          • 1970-01-01
          • 1970-01-01
          • 2014-07-21
          • 2016-01-19
          • 1970-01-01
          • 2019-09-12
          • 2013-10-08
          相关资源
          最近更新 更多