Question

%%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for...

%%%%Python Question%%%

Work from the template acrostic.py, which you can find on the ELMS page for this assignment. • In the Generator class, write an __init__() method with two parameters: self and the path to a text file containing one word per line. This method should read the words from the file, strip off leading and trailing whitespace, and store them in a dictionary where each key is a lower-case letter and each corresponding value is a list of words that start with that letter. For example, if you read in the words "dog", "horse", "cat", "dolphin", "hamster", and "duck", you would make this dictionary: {"c": ["cat"], "d": ["dog", "dolphin", "duck"], "h": ["horse", "hamster"]} Store the dictionary in an attribute called words. Hint: each time you read a new word from the file, determine what dictionary key the word should be stored under. If that key is not in the dictionary already, set the key equal to an empty list. Then, outside of your if statement, append the word to the list. • Also in the Generator class, write a generate() method with two parameters: self and a string that you will use to generate an acrostic. This method should build a list. Iterate over each character in the string that was passed in as an argument. If the lower-case version of the character is a key in self.words, randomly choose one of the words from self.words that starts with that letter, and add it to your list; otherwise, just add the character directly to your list. When you have finished iterating, instantiate a new Acrostic object, passing in your list as an argument. Return the Acrostic object you just created. Hint: random.choice() is your friend. • In if __name__ == "__main__":, do the following: ∘ Grab the first two command line arguments after the name of the script. The first one should be a path to a text file that consists of one word per line. The second one should be a string to convert into an acrostic. ∘ Create an instance of the Generator class, passing in the first command line argument. ∘ Call the generate() method of your Generator instance, passing in the second command line argument. Print the result. • Write class and method docstrings for the Generator class. When you run your script, be sure to provide two command-line arguments: a path to a word list file, and a string to convert into an acrostic.

""" Generate acrostics at random. """

import random

import sys

class Acrostic:

""" An acrostic.

Attributes:

lines (list of str): a list consisting of the lines of the

acrostic.

"""

def __init__(self, lines):

if not all([isinstance(line, str) for line in lines]):

raise ValueError("Not all items in lines are strings")

self.lines = lines

def __str__(self):

""" Return a string representation of the acrostic. """

return "\n".join(self.lines)

def msg(self):

""" Extract the message from which the acrostic was generated. """

return "".join([line[0] for line in self.lines])

class Generator:

""" Please put a proper docstring here """

# please put some methods here

if __name__ == "__main__":

# please put some code here

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

The question is pretty straight forward , I have documented the code do read it properly,

Check below images for output screenshot and image of the code as in python indentation must be correct

Code

import random

import sys

class Acrostic:

""" An acrostic.
  
Attributes:
  
lines (list of str): a list consisting of the lines of the
  
acrostic.
  
"""
  
def __init__(self, lines):
  
if not all([isinstance(line, str) for line in lines]):
  
raise ValueError("Not all items in lines are strings")
  
self.lines = lines

  
def __str__(self):
  
""" Return a string representation of the acrostic. """
  
return "\n".join(self.lines)
  
def msg(self):
  
""" Extract the message from which the acrostic was generated. """
  
return "".join([line[0] for line in self.lines])
  
class Generator:

"""
attribute : words -> dictionary storing the list of words
  
__init__
reads word line by line from the path provided in the parameter , creates a dictionary as mentioned
in the question and assign the value to the words attribute of the class
  
generate()
return a Acoustic object from the string parameter passed to it.
"""
  
# please put some methods here
words={}
def __init__(self,path):
f = open(path, "r")
while True:
word=f.readline()
if not word:
break
word=word.strip()
if word[0] not in self.words.keys():
self.words[word[0]]=[]
self.words[word[0]].append(word)
  
def generate(self,string):
list=[]
for i in string:
if i.lower() in self.words.keys():
temp_lst=self.words[i.lower()]
list.append(random.choice(temp_lst))
else:
list.append(i)
acr=Acrostic(list)
return acr
  
  
  
if __name__ == "__main__":

# please put some code here
pth=sys.argv[1]
string=sys.argv[2]
  
gen=Generator(pth)
Acr=gen.generate(string)
print(Acr)

Output

Code Screenshot :

Add a comment
Know the answer?
Add Answer to:
%%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for...
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
  • Hey I have a task which consists of two part. Part A asks for writing a...

    Hey I have a task which consists of two part. Part A asks for writing a program of WORD & LINE CONCORDANCE APPLICATION in python which I have completed it. Now the second part has given 5 dictionary implementation codes namely as: (ChainingDict, OpenAddrHashDict with linear probing, OpenAddrHashDict with quadratic probing, and 2 tree-based dictionaries from lab 12 (BST-based dictionary implementation) and asks for my above program WORD & LINE CONCORDANCE APPLICATION  to use these implemented code and show the time...

  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed...

    Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed by words from the file who’s filename is provided as an argument. It uses the words as keys and the count of occurrences as values. It returns the dictionary it constructed. It can use the ‘tokenize()’ function that is provided in the lecture slides. b. inverse_dict(dict) – This method takes a dictionary (generated by build_word_dictionary() and inverts it (as was done with students and...

  • Dictionary.java DictionaryInterface.java Spell.java SpellCheck.java In this lab you will write a spell check program. The program...

    Dictionary.java DictionaryInterface.java Spell.java SpellCheck.java In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the input file to be spell checked. The program will read in the words for the dictionary, then will read the input file and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is, add...

  • In Python !!! In this exercise you will continue to work with Classes and will build...

    In Python !!! In this exercise you will continue to work with Classes and will build on the Book class in Lab 13.10; you should copy the code you created there as you will need to extend it in this exercise. You will extend the Book class to accommodate the case where there may be multiple authors for a book. The attribute author should become a list. The constructor will still take a parameter that is a string for author,...

  • 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...

  • 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...

  • Hi, can someone offer input on how to address these 4 remain parts the zybook python...

    Hi, can someone offer input on how to address these 4 remain parts the zybook python questions?   4: Tests that get_num_items_in_cart() returns 6 (ShoppingCart) Your output ADD ITEM TO CART Enter the item name: Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in <module> passed = test_passed(test_passed_output_file) File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 8, in test_passed cart.add_item(item1) File "/home/runner/local/submission/unit_test_student_code/main.py", line 30, in add_item item_name = str(input('Enter the item name:\n')) EOFError: EOF when reading a line 5: Test that get_cost_of_cart() returns 10 (ShoppingCart)...

  • Rewrite Grammar with python Better pictures. this is only one question 2. Now we can begin on our LSystem clas...

    Rewrite Grammar with python Better pictures. this is only one question 2. Now we can begin on our LSystem class. First, we have to write a method that does the rewriting in the grammar. The idea here is that you start out with an axiom which is just a string. Then you apply rewrite rules, called productions, to expand some or all of the letters in the axiom to create a string, called a derived word. You can rewrite the...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

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