Remove whitespaces from the list in Python

3

I'm reading a file, stopwords.txt , and in this file each stopword is in a line,

a


o


para

Each stopword I am saving in a list as follows:

with open(sys.argv[1],"r") as file_entrada: 
    lista_nome_base_docs = [line.rstrip() for line in file_entrada]


with open(sys.argv[2],"r") as file_stopwords:  
    lista_stopwords = [line.strip() for line in file_stopwords]

After reading this, I would like to display the list on the screen and go out like this

Between the stopwords , there is a blank space, for example: ['a','','para']

How do I not see these white spaces in the list?

    
asked by anonymous 05.10.2017 / 15:09

1 answer

3

Just do the verification when you generate the word list:

lista_stopwords = [line.strip() for line in file_stopwords if line.strip() != ""]

Notice the addition of the if line.strip() != "" condition to the end of the line. This will ensure that only rows containing content other than line break are not included in the list.

See an example:

words = ["a\n", "\n", "ok\n", "\n", ""]

print([word.strip() for word in words if word.strip() != ""])

# ['a', 'ok']

See working at Ideone | Repl.it

    
05.10.2017 / 15:20