Antonio Maestre
Antonio Maestre

Reputation: 123

How to insert the words of a file in a list?

im programming in Python and I have next functions:

def devPalabras(nombreF):
    """Receive a file and returns each word in the file
        syntax: palabra.devPalabras(<fichero.txt>)"""

    if str(nombreF):
        file=open(nombreF,'r')
    else:
        return -1
    data = file.readlines()
    contador = 0
    for renglon in data:
        for palabra in renglon.split(' '):
            contador+=1
            print palabra

And I call function in main program as:

palabras = [] #Create a empty list of words
for palabra in devPalabras("palabras.txt"):
    palabras.append(palabra)

And finally, I want to print this list:

print palabras

Well, I get next Error when I compile my program:

TypeError: 'NoneType' object is not iterable

How can I resolve this?

Upvotes: 1

Views: 72

Answers (2)

Zectbumo
Zectbumo

Reputation: 4471

You have several issues in your code. 1) your devPalabras function normally returns None. This is the default if you don't return anything in a function.

2) if str(nombreF) is not the proper way to check if it is a string. Use isinstance(nombreF, str)

3) You will have a problem iterating later when your function returns a -1. Raise an exception instead.

4) Simply splitting the line with ' ' will result in the last word ending with a line feed. Strip this linefeed.

I believe this is what you are looking for:

def devPalabras(nombreF):
    """Receive a file and returns each word in the file
    syntax: palabra.devPalabras(<fichero.txt>)"""

    file=open(nombreF,'r')
    data = file.readlines()
    contador = 0
    for renglon in data:
        for palabra in renglon.split(' '):
            contador+=1
            yield palabra.strip()

palabras = [] #Create a empty list of words
for palabra in devPalabras("palabras.txt"):
    palabras.append(palabra)

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

Besides of the return -1, you are not returning any result, so the call devPalabras("palabras.txt") returns None by default.

What you could do, is to create a list, let's say listOfPalabras and each time you print palabra, add it to the list:

listOfPalabras = [] # creates a list

for renglon in data:
    for palabra in renglon.split(' '):
        contador+=1
        listOfPalabras.append(palabra) # add each element you want to the list

And at the end of the function, you can return the list:

return listOfPalabras

Upvotes: 1

Related Questions