首页 > 解决方案 > 需要有关此错误的帮助:只能将列表(而不是“str”)连接到列表

问题描述

我正在学习python,所以我对它很陌生。我一直在做课堂作业,但我遇到了一些错误,比如标题中的错误。

这是我的代码:

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()

但是,每当我运行它时,我都会收到此错误:

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

现在,我知道有很多这样的问题,但我尝试了很多时间,我无法解决它,我是编程新手,所以从上周开始我一直在学习基础知识。

谢谢

标签: pythonstringlist

解决方案


在这里,我稍微修改了函数 - 它会将每个单词提取到tuple. 用于with打开文件 - 一旦获取值,它将关闭指针。

我希望这对你有用!

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)

推荐阅读