python - 需要有关此错误的帮助:只能将列表(而不是“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.
现在,我知道有很多这样的问题,但我尝试了很多时间,我无法解决它,我是编程新手,所以从上周开始我一直在学习基础知识。
谢谢
解决方案
在这里,我稍微修改了函数 - 它会将每个单词提取到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)
推荐阅读
- python - 在 Python、Django 中将商品添加到购物车。/add/1 处的 FieldError -> 无法将关键字“book”解析为字段。选择是:作者,
- ios - Nativescript tns 发布 ios 无法可靠运行,因为 Apple 在 App Store Connect 上强制执行 2FA
- html - 在 React 上使用正则表达式删除最后一个字符
- android - 'A' 标签属性强制浏览器打开它
- xamarin - ZXing 二维码扫描器 Xamarin
- python - Discord.py - 播放音乐时出错 DownloadError: ERROR
- load - 如何在不需要重复按 Enter 按钮的情况下加载 ybsql 结果?
- c# - 1 个输出程序集中的 C# 多个构建配置
- python - Python 中的 Julia Plot(简短的重新编码帮助)
- loops - 我如何使用 Do 循环(或其他东西)来自动执行此操作?SAS