In this lab, you will use files that contain lists of names, prefixes, and occup
ID: 3929770 • Letter: I
Question
In this lab, you will use files that contain lists of names, prefixes, and occupations to generate names for Dungeons and Dragons characters. Write a python program that opens a file, reads all of the lines into a list of strings, and closes the file. Use the Readlines() method. Test your programming using the names.txt file provided. Convert the program into a function called loadFile, that receives the file name as a paramenter and returns an list of strings. Write a main routine that calls loadFile three times to load the three data files given into three lists. Then choose a random element from the title list, two from the name list, and one from the descriptor list to generate a name. Print the name be in the form shown (you have to add the "the"): title name the descriptor For example: King Ludovicus Botolf the Bowman Print the name to the screen.Explanation / Answer
#The python program that reads three text files using loadFile method
#and generates a random indexes of titleList, nameList and descriptor list
#and print to console.
import random
def main():
titleList=loadFile('title.txt')
nameList=loadFile('names.txt')
desciptorList=loadFile('descriptor.txt')
#generate four random numbers from the lists
r1=random.randint(0,len(titleList)-1)
r2=random.randint(0,len(nameList)-1)
r3=random.randint(0,len(nameList)-1)
r4=random.randint(0,len(desciptorList)-1)
#prnt to console
print('%s%s%s%s'%(titleList[r1],nameList[r2],nameList[r2],desciptorList[r4]))
#Method that reads given text file
def loadFile(filename):
fopen=open(filename,"r")
lines=fopen.readlines()
return lines
main()
----------------------------------------------------------------------------------------------------
Note :Use your own input text files and run the program in python 3
----------------------------------------------------------------------------------------------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.