Python - remover palavras irrelevantes

Palavras irrelevantes são palavras em inglês que não acrescentam muito significado a uma frase. Eles podem ser ignorados com segurança sem sacrificar o significado da frase. Por exemplo, as palavras como the, he, have etc. Tais palavras já estão capturadas neste corpus denominado corpus. Primeiro, baixamos para nosso ambiente python.

import nltk
nltk.download('stopwords')

Ele baixará um arquivo com palavras de interrupção em inglês.

Verificando as palavras irrelevantes

from nltk.corpus import stopwords
stopwords.words('english')
print stopwords.words() [620:680]

Quando executamos o programa acima, obtemos a seguinte saída -

[u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', 
u"she's", u'her', u'hers', u'herself', u'it', u"it's", u'its', u'itself', u'they', u'them', 
u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', 
u'that', u"that'll", u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be',
u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing',
u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until',
u'while', u'of', u'at']

Os vários idiomas diferentes do inglês com essas palavras irrelevantes são os seguintes.

from nltk.corpus import stopwords
print stopwords.fileids()

Quando executamos o programa acima, obtemos a seguinte saída -

[u'arabic', u'azerbaijani', u'danish', u'dutch', u'english', u'finnish', 
u'french', u'german', u'greek', u'hungarian', u'indonesian', u'italian', 
u'kazakh', u'nepali', u'norwegian', u'portuguese', u'romanian', u'russian',
u'spanish', u'swedish', u'turkish']

Exemplo

Usamos o exemplo abaixo para mostrar como as palavras irrelevantes são removidas da lista de palavras.

from nltk.corpus import stopwords
en_stops = set(stopwords.words('english'))
all_words = ['There', 'is', 'a', 'tree','near','the','river']
for word in all_words: 
    if word not in en_stops:
        print(word)

Quando executamos o programa acima, obtemos a seguinte saída -

There
tree
near
river