Question

Please write a python code for the following. Use dictionaries and list comprehensions to implement the...

Please write a python code for the following. Use dictionaries and list comprehensions to implement the functions defined below. You are expected to re-use these functions in implementing other functions in the file. Include a triple-quoted string at the bottom displaying your output.

Here is the starter outline for the homework:

d.

def count_words(text):

""" Count the number of words in text """

return 0

e.

def words_per_sentence(text):

return 0.0

f.

def word_count(text, punctuation=".,?;"):

""" Return a dictionary of word:count pairs.

(words are the keys, counts are the values). """

gettysburg_address = """

Four score and seven years ago our fathers brought forthon this continent, a new nation, conceived in Liberty,and dedicated to the proposition that all men are createdequal. Now we are engaged in a great civil war, testingwhether that nation, or any nation so conceived and sodedicated, can long endure. We are met on a greatbattlefield of that war. We have come to dedicate aportion of that field, as a final resting place forthose who here gave their lives that that nation mightlive. It is altogether fitting and proper that we shoulddo this. But, in a larger sense, we can not dedicate, wecan not consecrate, we can not hallow this ground.The brave men, living and dead, who struggled here,have consecrated it, far above our poor power to addor detract. The world will little note, nor longremember what we say here, but it can never forget whatthey did here. It is for us the living, rather, to bededicated here to the unfinished work which they whofought here have thus far so nobly advanced. It israther for us to be here dedicated to the great taskremaining before us—that from these honored dead wetake increased devotion to that cause for which theygave the last full measure of devotion that we herehighly resolve that these dead shall not have died invain that this nation, under God, shall have a newbirth of freedom and that government of the people, bythe people, for the people, shall not perish from theearth.

"""

Homework Answers

Answer #1

def count_words(text:str)->int:
    #First split the string into separate lines
    lines = text.split("\n")
    count = 0
    #For each line in text, do this
    for line in lines:
        #List of punctuations to remove from text
        punctuations = list(",.?!:'\"")
        #Check for each character in text
        for char in line:
            if char in punctuations:
                line = line.replace(char, "")
        #Now split string using whitespace
        lst = line.split(" ")
        #Do not count any empty string
        for i in range(len(lst)):
            if len(lst[i])!=0:
                count += 1
  
    return count

def words_per_sentence(text:str)->float:
    """Function to calculate average words per sentence in the text"""
    sentences = text.split(". ")
    #List to store the word count for each sentence
    lst = []
    for sentence in sentences:
        lst.append(count_words(sentence))
  
    #Calculate word per sentence
    wps = sum(lst)/len(lst)
  
    return wps

def word_count(text, punctuation=".,?;"):
    #List of all the words
    words = []
    #Dictionary for storing word count
    count_dict = dict()
  
    #First split the string into separate lines
    lines = text.split("\n")
    #For each line in text, do this
    for line in lines:
       #Check for each character in text
        for char in line:
            if char in punctuation:
                line = line.replace(char, "")
        #Now split string using whitespace
        lst = line.split(" ")
        #Append non-empty string to list words
        for s in lst:
            if len(s)>0:
                words.append(s)
      
    #Generate dictionary now
    for word in words:
        if word in count_dict.keys():
            count_dict[word] += 1
        else:
            count_dict[word] = 1
  
    return count_dict
          
def main():
    gettysburg_address = """
    Four score and seven years ago our fathers brought forthon this continent, a new nation, conceived
    in Liberty,and dedicated to the proposition that all men are createdequal. Now we are engaged in a
    great civil war, testingwhether that nation, or any nation so conceived and sodedicated, can long
    endure. We are met on a greatbattlefield of that war. We have come to dedicate aportion of that
    field, as a final resting place forthose who here gave their lives that that nation mightlive. It is
    altogether fitting and proper that we shoulddo this. But, in a larger sense, we can not dedicate,
    we can not consecrate, we can not hallow this ground.The brave men, living and dead, who struggled
    here,have consecrated it, far above our poor power to addor detract. The world will little note, nor
    longremember what we say here, but it can never forget whatthey did here. It is for us the living,
    rather, to bededicated here to the unfinished work which they whofought here have thus far so
    nobly advanced. It israther for us to be here dedicated to the great taskremaining before us—that
    from these honored dead wetake increased devotion to that cause for which theygave the last full
    measure of devotion that we herehighly resolve that these dead shall not have died invain that this
    nation, under God, shall have a newbirth of freedom and that government of the people, bythe
    people, for the people, shall not perish from theearth.
    """
  
    print("Count of words = ", count_words(gettysburg_address))
    print("Words per sentence = ", words_per_sentence(gettysburg_address))
    print("Word count:")
    print(word_count(gettysburg_address))
  
if __name__=="__main__":
    main()

Know the answer?
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
Similar Questions
Write a Python 3 program called “parse.py” using the template for a Python program that we...
Write a Python 3 program called “parse.py” using the template for a Python program that we covered in this module. Note: Use this mod7.txt input file. Name your output file “output.txt”. Build your program using a main function and at least one other function. Give your input and output file names as command line arguments. Your program will read the input file, and will output the following information to the output file as well as printing it to the screen:...
write a code in python Write the following functions below based on their comments. Note Pass...
write a code in python Write the following functions below based on their comments. Note Pass is a key word you can use to have a function the does not do anything. You are only allowed to use what was discussed in the lectures, labs and assignments, and there is no need to import any libraries. #!/usr/bin/python3 #(1 Mark) This function will take in a string of digits and check to see if all the digits in the string are...
Give 3-5 examples of how FDR mentioned land labor and capital public works as part of...
Give 3-5 examples of how FDR mentioned land labor and capital public works as part of the engine of economic recovery. HERE IS THE PASSAGE: “I am certain my fellow Americans......This great Nation will endure as it has endured, will revive and will prosper. So, first of all, let me assert my firm belief that the only thing we have to fear is fear itself—nameless, unreasoning, unjustified terror which paralyzes needed efforts to convert retreat into advance. In every dark...
Use python language please #One of the early common methods for encrypting text was the #Playfair...
Use python language please #One of the early common methods for encrypting text was the #Playfair cipher. You can read more about the Playfair cipher #here: https://en.wikipedia.org/wiki/Playfair_cipher # #The Playfair cipher starts with a 5x5 matrix of letters, #such as this one: # # D A V I O # Y N E R B # C F G H K # L M P Q S # T U W X Z # #To fit the 26-letter alphabet into...
**please write code with function definition taking in input and use given variable names** for e.g....
**please write code with function definition taking in input and use given variable names** for e.g. List matchNames(List inputNames, List secRecords) Java or Python Please Note:    * The function is expected to return a STRING_ARRAY.      * The function accepts following parameters:      *  1. STRING_ARRAY inputNames      *  2. STRING_ARRAY secRecords      */ Problem Statement Introduction Imagine you are helping the Security Exchange Commission (SEC) respond to anonymous tips. One of the biggest problems the team faces is handling the transcription of the companies reported...
Chapter 9 is about decision making. please read the comment and response and In 3-4 paragraphs....
Chapter 9 is about decision making. please read the comment and response and In 3-4 paragraphs. Please discuss your input/opinion. The focus of our discussion will be this article that I read in last week's New York Times. This is an open ended discussion with no framing question. I have gained tremendous insight reading the comments on this blog. One in particular really struck me recently. It came in response to a post that I had written quite a while...
Brian Durkee/ Director of Operations, Numi Organic Tea: Well Numi; Numi’s is a triple bottom line...
Brian Durkee/ Director of Operations, Numi Organic Tea: Well Numi; Numi’s is a triple bottom line company which means our focuses are on people, planet and profit. Hi, I’m Brian Durkee. I’m the director of operations for Numi Organic Tea and a big part of my role at Numi is to really manage that, and uh; it’s beyond just taking care of your employees. Numi has fifty employees in the U.S. but the peoples who dedicate the majority of their...
Actually a HISTORY question: what tactics does Einhard use to portray Charlemagne in "Life of Charlemagne"...
Actually a HISTORY question: what tactics does Einhard use to portray Charlemagne in "Life of Charlemagne" and what tactics does Procipius use to describe Justinian in a positive light in the "Nika Riots"? Ive posted both excerpts. "Life of Charlemagne" Charles the Great, (Charlemagne in French) reigned 768-814 as king of the Franks and the most important ruler of the Carolingian Dynasty, conquering lands in what is now Germany, France, Spain, and Italy. On Christmas Day 800 C.E., Pope Leo...
History: Offer an analysis of the articles included in the following articles: Science Fiction. Do you...
History: Offer an analysis of the articles included in the following articles: Science Fiction. Do you think the article offers a valid interpretation of the content offered in the current or previous chapters? Use an example to support your viewpoint. Minimum 250 words "Why Sci-Fi Keeps Imagining the Subjugation of White People" As much as the genre imagines the future, it also remixes the past—often by envisioning Western-style imperialism visited on the Western world. Science-fiction "contemplates possible futures." So says...
Taco Bell is part of Yum! Brands, which includes chains such as KFC and Pizza Hut....
Taco Bell is part of Yum! Brands, which includes chains such as KFC and Pizza Hut. The case reports an interview with Nick Dawson, the general manager for Taco Bell in the UK and Europe charged with introducing and expanding the Taco Bell chain in the region. Mr. Dawson discusses the franchise model of market entry and how Taco Bell develops its franchisees to succeed. 1. How would you assess Mr. Dawson's qualifications to hold his current position? Does he...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT