如何让我的代码在单独的行上打印一个字符的名称10次?

2024-10-02 20:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我正在写一个代码,生成十个地牢和龙的角色。我需要生成十个字符,他们应该是一个字符在每一行。以下是我老师的指示: “修改程序以生成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()

下面是我从修改后的代码中得到的输出:This image shows the output I am getting from my modified code. I'm getting a bunch of lines when I'm supposed to only generate ten character names with one on each line


Tags: txtlendefrandomarrayfiledescriptorsarr
2条回答

dumpfile在循环的每次迭代中都被调用。把它放在循环之后。另外(我确信您知道),您不是在读取文件dumpfile,而是在打印到终端。你知道吗

你可以这样做

names = '\n'.join(arr)
#print(names)
file.write(names)

在关闭文件之前。你知道吗

假设文件中有默认名称“原始名称.txt“,我会这样做:

def readnames(file):
with open(file) as f:
    return f.read().splitlines()

def choosepos(max):
    from random import randint
    return randint(0, max-1)

def main():
    orignames = readnames('originalnames.txt')
    choosenames = list()
    for n in range(5): # number of names that you wnat
        npos = choosepos(len(orignames))
        print(npos)
        choosenames.append(orignames[npos])
        orignames.remove(orignames[npos]);
    # instead of print, you write on your file
    print(choosenames)

main()

相关问题 更多 >