2011-03-30 60 views
73

Así que tienen un conjunto de datos que me gustaría eliminar las palabras vacías de usarCómo quitar las palabras vacías utilizando NLTK o pitón

stopwords.words('english') 

estoy luchando cómo utilizar esta dentro de mi código para simplemente sacar estas palabras. Ya tengo una lista de las palabras de este conjunto de datos, la parte con la que estoy luchando es compararla con esta lista y eliminar las palabras de finalización. Se agradece cualquier ayuda.

+4

¿De dónde sacó las palabras vacías de? ¿Esto es de NLTK? –

+25

@ MattO'Brien 'from nltk.corpus import stopwords' for future googlers – danodonovan

+11

También es necesario ejecutar' nltk.download ("stopwords") 'para que el diccionario de stopword esté disponible. – sffc

Respuesta

14

Supongo que tiene una lista de palabras (word_list) de la cual quiere eliminar las palabras vacías. Se podría hacer algo como esto:

filtered_word_list = word_list[:] #make a copy of the word_list 
for word in word_list: # iterate over word_list 
    if word in stopwords.words('english'): 
    filtered_word_list.remove(word) # remove word from filtered_word_list if it is a stopword 
+3

esto será mucho más lento que la comprensión de la lista de Daren Thomas ... – drevicko

147
from nltk.corpus import stopwords 
# ... 
filtered_words = [word for word in word_list if word not in stopwords.words('english')] 
+0

Gracias a ambas respuestas, ambas funcionan aunque lo haría Parece que tengo un error en mi código que impide que la lista de detención funcione correctamente. ¿Debería ser esta una nueva publicación de pregunta? no estoy seguro de cómo funcionan las cosas por aquí todavía! – Alex

+29

Para mejorar el rendimiento, considere '' 'stops = set (stopwords.words (" english "))' '' en su lugar. – isakkarlsson

+1

>>> import nltk >>> nltk.download() [Fuente] (http://www.nltk.org/data.html) –

19

También puede hacer un diff conjunto, por ejemplo:

list(set(nltk.regexp_tokenize(sentence, pattern, gaps=True)) - set(nltk.corpus.stopwords.words('english'))) 
+6

Nota: esto convierte la oración en un SET que elimina todas las palabras duplicadas y por lo tanto, no podrá usar el conteo de frecuencias en el resultado –

0
import sys 
print ("enter the string from which you want to remove list of stop words") 
userstring = input().split(" ") 
list =["a","an","the","in"] 
another_list = [] 
for x in userstring: 
    if x not in list:   # comparing from the list and removing it 
     another_list.append(x) # it is also possible to use .remove 
for x in another_list: 
    print(x,end=' ') 

    # 2) if you want to use .remove more preferred code 
    import sys 
    print ("enter the string from which you want to remove list of stop words") 
    userstring = input().split(" ") 
    list =["a","an","the","in"] 
    another_list = [] 
    for x in userstring: 
     if x in list:   
      userstring.remove(x) 
    for x in userstring:   
     print(x,end = ' ') 
    #the code will be like this 
0

puede utilizar esta función, se debe notar que necesita para reducir todas las palabras

from nltk.corpus import stopwords 

def remove_stopwords(word_list): 
     processed_word_list = [] 
     for word in word_list: 
      word = word.lower() # in case they arenet all lower cased 
      if word not in stopwords.words("english"): 
       processed_word_list.append(word) 
     return processed_word_list 
1

usando filter:

from nltk.corpus import stopwords 
# ... 
filtered_words = list(filter(lambda word: word not in stopwords.words('english'), word_list)) 
4

para excluir todos los tipos de palabras vacías que incluyen palabras vacías NLTK, se podría hacer algo como esto:

from many_stop_words import get_stop_words 
from nltk.corpus import stopwords 

stop_words = list(get_stop_words('en'))   #About 900 stopwords 
nltk_words = list(stopwords.words('english')) #About 150 stopwords 
stop_words.extend(nltk_words) 

output = [w for w in word_list if not w in stop_words] 
Cuestiones relacionadas