删除停用词和 string.punctuation

removing stop words and string.punctuation

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

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',...]

好像标点符号还在。我做错了什么?

在这行更改中尝试将 'or' 更改为 'and' 这样您的列表将 return 仅包含既不是停用词又不是标点符号的词。

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

必须是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:

后一种解决方案最快。

关闭。 您需要在比较中使用 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]