好吧,我正在写一个代码,生成十个地牢和龙的角色。我需要生成十个字符,他们应该是一个字符在每一行。以下是我老师的指示: “修改程序以生成10个名称并将它们存储在一个数组中。然后编写一个函数dumpFile,将数组写入一个名为CharacterNames.txt文件“文件中每行应有一个字符名。”
这是我的原始代码。你知道吗
import random
def main():
txt1 = loadFile("names.txt")
name_txt1 = random.randint(0, len(txt1))
name2_txt1 = random.randint(0, len(txt1))
txt2 = loadFile("titles.txt")
titles_txt2 = random.randint(0, len(txt2))
txt3 = loadFile("descriptors.txt")
descriptors_txt3 = random.randint(0, len(txt3))
print(txt2[titles_txt2], txt1[name_txt1], txt1[name2_txt1],"the", txt3[descriptors_txt3])
def loadFile(fileName):
array = []
file = open(fileName, "r")
for line in file:
array.append(line.strip())
file.close()
return(array)
main()
这是我到目前为止修改过的代码。你知道吗
import random
def main():
txt1 = loadFile ("names.txt")
txt2 = loadFile ("titles.txt")
txt3 = loadFile ("descriptors.txt")
array = []
for _ in range (10):
name_txt1 = dumpFile2 (txt1)
name2_txt1 = dumpFile2 (txt1)
titles_txt2 = dumpFile2 (txt2)
descriptors_txt3 = dumpFile2(txt3)
x = " ".join ((titles_txt2, name_txt1, name2_txt1, "the", descriptors_txt3))
array.append (x.strip())
dumpFile (array)
def loadFile (fileName):
with open (fileName) as file1: return file1.read ().splitlines ()
def dumpFile (arr):
file = open ("CharacterNames.txt", "w")
file.close()
print(arr)
def dumpFile2(arr):
return arr [random.randint(0, len(arr)- 1)]
main()
dumpfile
在循环的每次迭代中都被调用。把它放在循环之后。另外(我确信您知道),您不是在读取文件dumpfile
,而是在打印到终端。你知道吗你可以这样做
在关闭文件之前。你知道吗
假设文件中有默认名称“原始名称.txt“,我会这样做:
相关问题 更多 >
编程相关推荐