I'm taking an intro programming class and am working ahead on some assignments that aren't due for a few weeks. This one asks me to take three text files - names, titles, and descriptions - and use them to randomly generate "fantasy character" names. My code runs and does what I want it to, but I feel like it's cluttered and could be cleaned up quite a bit. Keep in mind that this is an INTRO course and in class have just covered basic boolean logic, loops, arrays, etc.; not classes, object-oriented, or any advanced stuff (I'm trying to learn some of this on my own).
import random
def main():
for i in range(10):
# Load names, titles, descriptions into arrays
names = loadFile('names.txt')
title = loadFile('titles.txt')
descriptor = loadFile('descriptors.txt')
# Generate random number based on list length
nameListLength = len(names)
titleListLength = len(title)
descListLength = len(descriptor)
firstNameIndex = random.randrange(nameListLength)
lastNameIndex = random.randrange(nameListLength)
randTitleIndex = random.randrange(titleListLength)
randDescriptor = random.randrange(descListLength)
# Choose random list entry
firstName = names[firstNameIndex]
lastName = names[lastNameIndex]
title2 = title[randTitleIndex]
description = descriptor[randDescriptor]
nameList = [title2, firstName, lastName, description]
dumpFile(nameList)
print(title2, firstName, lastName, 'the', description)
print()
print('These names have been written to \"CharacterNames.txt\".')
def dumpFile(nameList):
title = str(nameList[0])
firstName = str(nameList[1])
lastName = str(nameList[2])
descriptor = str(nameList[3])
outfile = open('CharacterNames.txt', 'a')
outfile.write(title + ' ' + firstName + ' ' + lastName + ' ' +
'the' + ' ' + descriptor + '\n')
outfile.write('\n')
outfile.close()
def loadFile(nameFile):
nameList = open(nameFile, 'r')
nameArray = []
for line in nameList:
name = line
name = name.rstrip('\n')
nameArray.append(name)
nameList.close()
return nameArray
main()
Aucun commentaire:
Enregistrer un commentaire