h97
h97

Reputation: 1

need help regarding this error: can only concatenate list (not "str") to list

I'm learning python so I am pretty new to it. I've been working on a class assignment and iv'e been facing some error, such as the one in the title.

This is my code:

import random

def getWORDS(filename):         
   f = open(filename, 'r')
   templist = []
   for line in f:
        templist.append(line.split("\n"))
   return tuple(templist)


articles = getWORDS("articles.txt")
nouns = getWORDS("nouns.txt")
verbs = getWORDS("verbs.txt")
prepositions = getWORDS("prepositions.txt")

def sentence():
    return nounphrase() + " " + verbphrase()

def nounphrase():
    return random.choice(articles) + " " + random.choice(nouns)

def verbphrase():
    return random.choice(verbs) + " " + nounphrase() + " " +  \
           prepositionalphrase()

def prepositionalphrase():
    return random.choice(prepositions) + " " + nounphrase()
def main():
    number = int(input("enter the number of sentences: "))
    for count in range(number):
        print(sentence())
main()

However, whenever I run it I get an this error:

TypeError: can only concatenate list (not "str") to list.

Now, I know there are tons of question like this but I tried a lot of time, I am not able to fix it, I'm new to programming so I've been learning the basics since last week.

Thank you

Upvotes: 0

Views: 312

Answers (4)

Parvathirajan Natarajan
Parvathirajan Natarajan

Reputation: 1324

Here I've modified the function slightly - it'll fetch every words into a tuple. Use with to open the files - it will close the pointer once the values have been fetched.

I hope this will work for you!

def getWORDS(filename):  
    result = []       
    with open(filename) as f:
        file = f.read()
        texts = file.splitlines()

        for line in texts:
            result.append(line)
    return tuple(result)

Upvotes: 1

Ittay Kohavi
Ittay Kohavi

Reputation: 7

This is how I would write the full code. (fixed file opening and reading + fixed capitalization)

import random

def getWORDS(filename):         
    with open(filename, 'r') as f:
        file = f.read()
        templist = file.split("\n")
    return tuple(templist)

articles = getWORDS("articles.txt")
nouns = getWORDS("nouns.txt")
verbs = getWORDS("verbs.txt")
prepositions = getWORDS("prepositions.txt")

def sentence():
    sentence = nounphrase() + " " + verbphrase()
    sentence = sentence.split(" ")
    sentence[0] = sentence[0].capitalize()
    sentence = " ".join(sentence)
    return sentence

def nounphrase():
    return random.choice(articles).lower() + " " + random.choice(nouns).capitalize()

def verbphrase():
    return random.choice(verbs).lower() + " " + nounphrase() + " " +  \
           prepositionalphrase()

def prepositionalphrase():
    return random.choice(prepositions).lower() + " " + nounphrase()
def main():
    number = int(input("enter the number of sentences: "))
    for count in range(number):
        print(sentence())
main()

Upvotes: 0

Ittay Kohavi
Ittay Kohavi

Reputation: 7

When working with a file, you should use the read() method:

file = f.read()

To split the file to lines and add to a list, you first split, then append line by line.

file = f.read()
lines = file.split("\n")
for line in lines:
    templist.append(line)

In your case, you are using the list of lines as-is, so I would write:

file = f.read()
templist = file.split("\n")

Edit 1:

Another useful tool when working with files is f.readline(), which returns the first line when calling it for the first time, second when calling it once again... third... and so on, although the previous ways I showed would be more efficient here.

Edit 2:

When you are done using the file, use the close() method, or start using the file with a with ... as method which closes the file at the end of the code block.

Code example using with ... as (The best written code in this answer):

def getWORDS(filename):         
    with open(filename, 'r') as f:
        file = f.read()
        templist = file.split("\n")
    return tuple(templist)

Code example using close():

def getWORDS(filename):         
    f = open(filename, 'r')
    file = f.read()
    templist = file.split("\n")
    f.close()
    return tuple(templist)

Upvotes: 0

Terry Spotts
Terry Spotts

Reputation: 4075

I think the problem is in this line:

templist.append(line.split("\n"))

split() will return a list that is then appended to templist. If you're wanting to remove the newline character from the end of the line use rstrip() as this will return a string.

Upvotes: 0

Related Questions