Question

In: Computer Science

1)  Write a python program that opens a file, reads all of the lines into a list...

1)  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 programing using the names.txt file provided.
2) Convert the program into a function called loadFile, that receives the file name as a parameter and returns a list of strings.
3) 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 name the descriptor
For example:
King Ludovicus Botolf the Bowman
Print the name to the screen.   
Submit your python file (.py) to Sakai

Part 2: Writing Files (Optional Extra Credit 20 pts)
Modify the program to generate 10 names and store them in a list.
Write a function, dumpFile that writes the list to a file called "CharacterNames.txt" There should be one Character Name on each line in the file.
Test the program to be sure it works

Im stumped at number 2

here is what i have for number 1



f = open('names.txt', 'r')
lines = f.readlines()
for line in range(len(lines)):
lines[line] = lines[line].rstrip()
print(lines)
f.close()

Solutions

Expert Solution

Part 1:

1)

Python program that reads all the lines of a file into a list of strings and closes the file.

Program:

lines=[]

# Store each line in a list

with open('input.txt') as file:

    lines = file.readlines()

# Remove new line in each string

lines = [i.strip() for i in lines]

file.close()

for i in lines:

    print(i)

Input text file (input.txt):

Jack

Micheal

Alex

Bob

Sample output:

2)

The loadFile function receives the file name as a parameter and returns a list of strings.

Program:

def loadFile(fileName):

    lines=[]

    with open(fileName) as file:

        lines = file.readlines()

    lines = [i.strip() for i in lines]

    file.close()

    return lines

lines=loadFile('input.txt')

print (lines)

Input text file (input.txt):

Jack

Micheal

Alex

Bob

Sample output:

3)

The complete program along with main function.

Program:

import random

def loadFile(fileName):

    lines=[]

    with open(fileName) as file:

        lines = file.readlines()

    lines = [i.strip() for i in lines]

    file.close()

    return lines

def main():

    # Call the loadFile function along with the text document as parameter

    title=loadFile('title.txt')

    name=loadFile('name.txt')

    descriptor=loadFile('descriptor.txt')

    # Generate random strings

    rand_title=title[random.randint(0,len(title)-1)]    

    rand_name1=name[random.randint(0,len(name)-1)]   

    rand_name2=name[random.randint(0,len(name)-1)]

    rand_desc=descriptor[random.randint(0,len(descriptor)-1)]

    # Print the output

    print(rand_title+" "+rand_name1+" "+rand_name2+" the "+rand_desc)

       

main()

Input text files:

title.txt:

Lord

King

Duke

Earl

Bishop

Count

Sir

Alderman

Admiral

Vicar

Monk

Archbishop

Prince

Cardinal

Chancellor

name.txt:

Ademar

Adelard

Aalart

Alart

Aldous

Aldis

Amaury

Aimeri

Amauri

Amery

Emericus

Alphonse

Alfan

Ancel

descriptor.txt:

Bald

Roses

Dragon

Lion Hearted

Bold

First

Second

Third

Fourth

Monk

Cute

Mighty

Bowman

Elf

Red

Strong

Dragonslayer

Giant

Sleuth

Evil

Car Salesman

Sample output:

Part 2:

Program:

import random

def loadFile(fileName):

    lines=[]

    with open(fileName) as file:

        lines = file.readlines()

    lines = [i.strip() for i in lines]

    file.close()

    return lines

def dumpFile(CharacterNames):

    file=open("CharacterNames.txt","w+")

    for i in CharacterNames:

        # Write each line to a text file

        file.write(i+"\n")

   

def main():

    # Call the loadFile function along with the text document as parameter

    title=loadFile('title.txt')

    name=loadFile('name.txt')

    descriptor=loadFile('descriptor.txt')

    CharacterNames=[]

    i=0

    while i<10:

        # Generate random strings

        rand_title=title[random.randint(0,len(title)-1)]    

        rand_name1=name[random.randint(0,len(name)-1)]   

        rand_name2=name[random.randint(0,len(name)-1)]

        rand_desc=descriptor[random.randint(0,len(descriptor)-1)]

        # Store the string in a list

        Charstr=rand_title+" "+rand_name1+" "+rand_name2+" the "+rand_desc

        CharacterNames.append(Charstr)

        i=i+1

    # Call the dumpFile function

    dumpFile(CharacterNames)

   

main()

Input text files:

title.txt:

Lord

King

Duke

Earl

Bishop

Count

Sir

Alderman

Admiral

Vicar

Monk

Archbishop

Prince

Cardinal

Chancellor

name.txt:

Ademar

Adelard

Aalart

Alart

Aldous

Aldis

Amaury

Aimeri

Amauri

Amery

Emericus

Alphonse

Alfan

Ancel

descriptor.txt:

Bald

Roses

Dragon

Lion Hearted

Bold

First

Second

Third

Fourth

Monk

Cute

Mighty

Bowman

Elf

Red

Strong

Dragonslayer

Giant

Sleuth

Evil

Car Salesman

Sample output:


Related Solutions

Write a program that opens the file: "Lab6A_Data", reads all the values from the file, and...
Write a program that opens the file: "Lab6A_Data", reads all the values from the file, and calculates the following: A) The number of values in the file B) The sum of all the values in the file (a running total) C) The average of all the values in the file. D) The minimum value. E) The maximum value. F) The range of the data set of values. G) The number of times the value: '357' occurrs in the file. Display...
Write a C ++ program which opens a file and reads several numbers, utilizing the fscanf()...
Write a C ++ program which opens a file and reads several numbers, utilizing the fscanf() function. Can you add few comments with explanations what is going on?
File Compare Write a program that opens two text files and reads their contents into two...
File Compare Write a program that opens two text files and reads their contents into two separate queues. The program should then determine whether the files are identical by comparing the characters in the queues. When two nonidentical characters are encountered, the program should display a message indicating that the files are not the same. If both queues contain the same set of characters, a message should be displayed indicating that the files are identical. // Copyright (c) 2013 __Pearson...
For C++ Write a program that opens a specified text file then displays a list of...
For C++ Write a program that opens a specified text file then displays a list of all the unique words found in the file. Hint: Store each word as an element of a set.
Question: Write a program in python that reads in the file climate_data_2017_numeric.csv and prompts the user...
Question: Write a program in python that reads in the file climate_data_2017_numeric.csv and prompts the user to enter the name of a field (other than Date), and then outputs the highest and lowest values recorded in that field for the month of August. The file climate_data_2017_numeric.csv contains the following fields: Date Minimum temperature (C) Maximum temperature (C) Rainfall (mm) Speed of maximum wind gust (km/h) 9am Temperature (C) 9am relative humidity (%) 3pm Temperature (C) 3pm relative humidity (%) Expected...
Java Code using Queue Write a program that opens a text file and reads its contents...
Java Code using Queue Write a program that opens a text file and reads its contents into a queue of characters, it should read character by character (including space/line change) and enqueue characters into a queue one by one. Dequeue characters, change their cases (upper case to lower case, lower case to upper case) and save them into a new text file (all the chars are in the same order as the original file, but with different upper/lower case) use...
Java Code using Stack Write a program that opens a text file and reads its contents...
Java Code using Stack Write a program that opens a text file and reads its contents into a stack of characters, it should read character by character (including space/line change) and push into stack one by one. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the first file. Ex input file: Good...
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
IN PYTHON: Write a program that displays the lines from the total.txt file in the following...
IN PYTHON: Write a program that displays the lines from the total.txt file in the following output. Use a try catch phrase to check for errors. Use only one function for this portion [main()]. Remember to use Python. Sample output below: 19 16, 29 3, 30 4, 34
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all...
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all the lyrics from a file named lyrics.txt that is to be found in the same directory as the running program. The program should read the lyrics for each line and treat each word as a token. If the line contains a double (an integer is also treated as a double) it should use the first double it finds in line as the timestamp for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT