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

时间:2016-07-07 11:34:18

标签: python python-3.x python-3.5

好的,所以我正在编写一个生成十个Dungeon和dragons角色的代码。我需要生成十个字符,每行应该是一个字符。这是我老师的指示: “修改程序以生成10个名称并将它们存储在一个数组中。然后编写一个函数,dumpFile将数组写入名为”CharacterNames.txt“的文件中。文件中每行应该有一个字符名称。” p>

所以这是我的原始代码。

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

2 个答案:

答案 0 :(得分:0)

在循环的每次迭代中调用

dumpfile。把它放在循环之后。另外(我相信你知道的),你没有读到文件dumpfile,只是打印到终端。

您可以执行类似

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

关闭文件之前。

答案 1 :(得分:0)

假设您在文件“originalnames.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()