Question

Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from...

Python 3

Modify the sentence-generator program of Case Study so that it inputs its vocabulary from a set of text files at startup. The filenames are nouns.txt, verbs. txt, articles.txt, and prepositions.txt.

(HINT: Define a single new function, getWords. This function should expect a filename as an argument. The function should open an input file with this name, define a temporary list, read words from the file, and add them to the list. The function should then convert the list to a tuple and return this tuple. Call the function with an actual filename to initialize each of the four variables for the vocabulary.)

Case Study: Generating Sentences code:

import random
articles = ("A", "THE")
nouns = ("BOY", "GIRL", "BAT", "BALL")
verbs = ("HIT", "SAW", "LIKED")
prepositions = ("WITH", "BY")

def sentence():
return nounPhrase() + " " + verbPhrase()
def nounPhrase():
return random.choice(articles) + " " + random.choice(nouns)
def verbPhrase():
return random.choice(verbs) + " " + nounPhrase() + " " + \
prepositionalPhrase()
def prepositionalPhrase():
return random.choice(prepositions) + " " + nounPhrase()
def main():
number = int(input("Enter the number of sentences: "))
for count in range(number):
print(sentence())
if __name__ == "__main__":
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

NOTE: I have completed answer for your question. Please check and let me know if you have any queries. I will get back to you within 24 hours. Thanks for your patience.

Before running the program you need to have these files created like below in your unix box.

Unix Terminal> cat nouns.txt

BOY

GIRL

BAT

BALL

Unix Terminal> cat articles.txt

A

THE

Unix Terminal> cat verbs.txt

HIT

SAW

LIKED

Unix Terminal> cat prepositions.txt

WITH

BY

Unix Terminal>

Code:

#!/usr/local/bin/python3

import random

def getWords(filename):

fp = open(filename)

temp_list = list()

for each_line in fp:

each_line = each_line.strip()

temp_list.append(each_line)

words = tuple(temp_list)

fp.close()

return words

articles = getWords('articles.txt')

nouns = getWords('nouns.txt')

verbs = getWords('verbs.txt')

prepositions = getWords('prepositions.txt')

def sentence():

return nounPhrase() + " " + verbPhrase()

def nounPhrase():

return random.choice(articles) + " " + random.choice(nouns)

def verbPhrase():

return random.choice(verbs) + " " + nounPhrase() + " " + prepositionalPhrase()

def prepositionalPhrase():

return random.choice(prepositions) + " " + nounPhrase()

def main():

number = int(input('Enter number of sentences: '))

for count in range(number):

print(sentence())

if __name__=='__main__':

main()

Code screenshot:

Code output screenshot:

Add a comment
Know the answer?
Add Answer to:
Python 3 Modify the sentence-generator program of Case Study so that it inputs its vocabulary from...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a program that will determine the even number(s) from a list of numbers. Your program...

    Create a program that will determine the even number(s) from a list of numbers. Your program should create and call a function FindEven that accepts a list of numbers and returns a list of only the even numbers in sorted order. Note that the original list is given in the starter code. def body(): numberlist = [1, 1000, 5, -3, 2, 16 # Write your code here and notice level # Do NOT include: if __name__ == been provided for...

  • python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a...

    python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script should also include a main function that allows the user to compute square roots of inputs until she presses the enter/return key. 2.Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton. (Hint: The estimate of...

  • ***NEED SOLUTION IN PYTHON *** 1. Create a main function which only gets executed when the...

    ***NEED SOLUTION IN PYTHON *** 1. Create a main function which only gets executed when the file is directly executed Hint: def main(): pass if __name__ == '__main__': main() 2. Your programs will use a file called scores.txt to store a bunch of user-provided numbers. These can be int or float but their values must be between 0 and 100. Inside the main function, display the current list of numbers to the user and ask if they want to update...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • The way I understand it is i'm trying to link a list that I read into...

    The way I understand it is i'm trying to link a list that I read into python from a cvs file to json and xml and pass the doctest. Please refere the lines where I show what I did below. home / study / engineering / computer science / questions and answers / """this script converts a csv file with headers ... Question: """This script converts a CSV file with headers to... Bookmark """This script converts a CSV file with...

  • My Python file will not work below and I am not sure why, please help me...

    My Python file will not work below and I am not sure why, please help me debug! ********************************* Instructions for program: You’ll use these functions to put together a program that does the following: Gives the user sentences to type, until they type DONE and then the test is over. Counts the number of seconds from when the user begins to when the test is over. Counts and reports: The total number of words the user typed, and how many...

  • Use of search structures! how can i make this program in python? Learning Objectives: You should...

    Use of search structures! how can i make this program in python? Learning Objectives: You should consider and program an example of using search structures where you will evaluate search trees against hash tables. Given the three text files under containing the following: - A list of students (classes Student in the distributed code) - A list of marks obtained by the students (classes Exam results in the distributed code) - A list of topics (classes Subject in the distributed...

  • ***How do I insert the Halloween text into this and write the program**** Topics: List, tuple...

    ***How do I insert the Halloween text into this and write the program**** Topics: List, tuple In this lab, you will write a scrambled word game.  The game starts by loading a file containing scrambled word-answer pair separated.  Sample of the file content is shown below.  Once the pairs are loaded, it randomly picks a scrambled word and has the player guess it.  The number of guesses is unlimited.  When the user guesses the correct answer, it asks the user if he/she wants another scrambled...

  • Use python Start: def main(): gradeList = []    fileName = getFile() gradeList = getData(fileName) mean...

    Use python Start: def main(): gradeList = []    fileName = getFile() gradeList = getData(fileName) mean = calculateMean(gradeList) sd = calculateSD(mean, gradeList) displayHeadings(gradeList, mean, sd) curveGrades(mean, sd, gradeList)       if __name__ == "__main__": main() For this program, you will create a grade curving program by reading grades from a file, calculating the mean and standard deviation. The mean is the average value of the grades and the standard deviation measures the spread or dispersal of the numbers from the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT