Convert a text file into a list

1

I am trying to convert a text file into a list, using Python. The text file are many words, one below the other.

What I did was this:

stop_words=open('stopwords.txt.txt','r') 

lineas = [linea.split() for linea in stop_words]

for linea in lineas:

      print(linea)

But what prints me are many lists one below the other with a single word. And what I want is a single list with all the words, separated by a comma.

    
asked by Estanislao Ortiz 21.11.2017 в 03:01
source

1 answer

1

str.split() what it does is take a string and divide it into substrings using the separator that is passed as the first argument. If no separator is passed, it is taken as such to any number of consecutive spaces, eliminating also those that are at the beginning and end of the chain. Since the output is a list, what you get when you apply split on each line is a list of lists.

If as you say, each line only contains one word, you do not need split for anything, in any case if you need str.strip / str.rstrip so that you delete the line break / carriage return and remain alone with the word:

with open('stopwords.txt.txt','r') as stop_words: 
    lineas = [linea.strip() for linea in stop_words]

for linea in lineas:
    print(linea)

For a file like the following:

  

hello
  world
  python

You will get a list like:

  

["hello", "world", "python"]

The str.strip method if no arguments are received removes all spaces, tabs, new line characters (\ n), and carriage returns (\ r) both at the beginning and at the end of the string.

If you want to get a list with the raw lines (without removing anything) you can simply use the readlines method:

lineas = stop_words.readlines()
    
answered by 21.11.2017 в 03:18