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
Using the string below to make a list of words, show that there are 272 words...
Using the string below to make a list of words, show that there are 272 words in the Gettysburg Address. How many distinct words are in the speech? Hint: You may need to delete some of the punctuation, including new lines, which are represented by \n. In [63]: gettysburg_address = """Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal....
You've been hired by Text Turtles to write a C++ console application that determines the reading...
You've been hired by Text Turtles to write a C++ console application that determines the reading grade level of the text in a file. The text comes from two files: SampleText1.txt and SampleText2.txt. Sample text1= It has often been said there's so much to be read you never can cram all those words in your head. So the writer who breeds more words than he needs is making a chore for the reader who reads. That's why my belief is...
Write a program in python that reads in the file quiztext (txt) and creates a list...
Write a program in python that reads in the file quiztext (txt) and creates a list of each unique word used in the file, then prints the list. Generate a report that lists each individual word followed by the number of times it appears in the text, for example: Frequency_list = [('was', 3), ('bird',5), ('it', 27)….] and so on. Note: Notice the structure: a list of tuples. If you're really feeling daring, Google how to sort this new list based...
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:...
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...
**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...
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...
PLEASE READ THE ARTICLES ATTACHED AND ANSWER THE FOLLOWING QUESTION. THE ARTICLES ARE BOTH LISTED PLEASE...
PLEASE READ THE ARTICLES ATTACHED AND ANSWER THE FOLLOWING QUESTION. THE ARTICLES ARE BOTH LISTED PLEASE PROVIDE DETAILED EXPLANATIONS. PLEASE WRITE ONE REFLECTION COMBINING BOTH ARTICLES. The purpose of the Article Reflection is to deepen your engagement with the topic of Epidemiology. It will give you the opportunity to reflect on the current real-life epidemiological issues at hand and help to bring meaning to them. ARTICLE 1: A group of students knew they had covid-19. They hosted a party over...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT