Question

Write a program in python that reads in the file quiztext (txt) and creates a list...

  1. 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.
  2. 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 on the second tuple value and see which word appears the most frequently…but that part is just for fun.
  3. Provide a list of word frequencies. Incorporate error checking, command line input, and the templated format discussed during this module.
  4. Be sure to submit both your code and output as separate documents for grading. Your code should be well documented, including any problems or incomplete parts, and should be commented to make your logic clear and easy to understand.

This is the quiztext (txt) below

I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation. Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity. But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself in exile in his own land. And so weâve come here today to dramatize a shameful condition. In a sense weâve come to our nationâs capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the unalienable rights of life, liberty, and the pursuit of happiness. It is obvious today that America has defaulted on this promissory note insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked insufficient funds. But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so weâve come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice. We have also come to this hallowed spot to remind America of the fierce urgency of now. This is no time to engage in the luxury of cooling off or to take the tranquilizing drug of gradualism. Now is the time to make real the promises of democracy. Now is the time to rise from the dark and desolate valley of segregation to the sunlit path of racial justice. Now is the time to lift our nation from the quicksands of racial injustice to the solid rock of brotherhood. Now is the time to make justice a reality for all of Godâs children. It would be fatal for the nation to overlook the urgency of the moment. This sweltering summer of the Negroâs legitimate discontent will not pass until there is an invigorating autumn of freedom and equality. 1963 is not an end, but a beginning. And those who hope that the Negro needed to blow off steam and will now be content will have a rude awakening if the nation returns to business as usual. There will be neither rest nor tranquility in America until the Negro is granted his citizenship rights. The whirlwinds of revolt will continue to shake the foundations of our nation until the bright day of justice emerges. But there is something that I must say to my people, who stand on the warm threshold which leads into the palace of justice: in the process of gaining our rightful place, we must not be guilty of wrongful deeds. Let us not seek to satisfy our thirst for freedom by drinking from the cup of bitterness and hatred. We must forever conduct our struggle on the high plane of dignity and discipline. We must not allow our creative protest to degenerate into physical violence. Again and again, we must rise to the majestic heights of meeting physical force with soul force. The marvelous new militancy which has engulfed the Negro community must not lead us to a distrust of all white people, for many of our white brothers, as evidenced

by their presence here today, have come to realize that their destiny is tied up with our destiny, and they have come to realize that their freedom is inextricably bound to our freedom. We cannot walk alone. And as we walk, we must make the pledge that we shall always march ahead. We cannot turn back. There are those who are asking the devotees of civil rights, When will you be satisfied? We can never be satisfied as long as the Negro is the victim of the unspeakable horrors of police brutality. We can never be satisfied as long as our bodies, heavy with the fatigue of travel, cannot gain lodging in the motels of the highways and the hotels of the cities. We cannot be satisfied as long as the Negroâs basic mobility is from a smaller ghetto to a larger one. We can never be satisfied as long as our children are stripped of their selfhood and robbed of their dignity by signs stating for whites only. We cannot be satisfied as long as a Negro in Mississippi cannot vote and a Negro in New York believes he has nothing for which to vote. No, no, we are not satisfied and we will not be satisfied until justice rolls down like waters and righteousness like a mighty stream. I am not unmindful that some of you have come here out of great trials and tribulations. Some of you have come fresh from narrow jail cells. Some of you have come from areas where your quest for freedom left you battered by the storms of persecution and staggered by the winds of police brutality. You have been the veterans of creative suffering. Continue to work with the faith that unearned suffering is redemptive. Go back to Mississippi, go back to Alabama, go back to South Carolina, go back to Georgia, go back to Louisiana, go back to the slums and ghettos of our northern cities, knowing that somehow this situation can and will be changed. Let us not wallow in the valley of despair. I say to you today, my friends, so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream. I have a dream that one day this nation will rise up and live out the true meaning of its creed: We hold these truths to be self-evident, that all men are created equal. I have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood. I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice. I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today. I have a dream that one day down in Alabama, with its vicious racists, with its governor having his lips dripping with the words of interposition and nullification, one day right there in Alabama little black boys and black girls will be able to join hands with little white boys and white girls as sisters and brothers. I have a dream today. I have a dream that one day every valley shall be exalted, every hill and mountain shall be made low, the rough places will be made plain, and the crooked places will be made straight, and the glory of the Lord shall be revealed, and all flesh shall see it together. This is our hope. This is the faith that I go back to the South with. With this faith we will be able to hew out of the mountain of despair a stone of hope. With this faith we will be able to transform the jangling discords of our nation into a beautiful symphony of brotherhood. With this faith we will be able to work together, to pray together, to struggle together, to go to jail together, to stand up for freedom together, knowing that we will be free one day. This will be the day, this will be the day when all of Godâs

children will be able to sing with new meaning: My country, tis of thee, sweet land of liberty, of thee I sing. Land where my fathers died, land of the pilgrimâs pride, from every mountainside, let freedom ring! And if America is to be a great nation, this must become true. So let freedom ring from the prodigious hilltops of New Hampshire. Let freedom ring from the mighty mountains of New York. Let freedom ring from the heightening Alleghenies of Pennsylvania. Let freedom ring from the snow-capped Rockies of Colorado. Let freedom ring from the curvaceous slopes of California. But not only that: Let freedom ring from Stone Mountain of Georgia. Let freedom ring from Lookout Mountain of Tennessee. Let freedom ring from every hill and molehill of Mississippi. From every mountainside, let freedom ring. And when this happens, and when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of Godâs children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual: âFree at last! Free at last! Thank God Almighty, we are free at last!

Homework Answers

Answer #1

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.

Code:

filepath ='C:\\Users\\Preeti\\Desktop\\DOCSSS\\quiztext.txt'
unique_word=[]
with open(filepath,'r') as file:
for line in file:   
for word in line.split():
word=word.strip('!')
word=word.strip(',')
word=word.strip('.')
if word not in unique_word:
unique_word.append(word)
  
  
print(unique_word)

Explanation:

1.We create an empty list named unique_word.

2.We open the file in read mode using open function and pass the filepath to the function .

3.Using for loop, we read every line in file and then we read every word in the line using split function and pass space as the parameter to split i.e.split(" "), if comma was the parameter to split then we wpuld have used split(",").

4.since many word has !(exclamation) ,(commas) and .(fullstop) after splitting . 2 similar words would still be treated as different words while finding unique word i.e Ring. and Ring! would be treated as different words.

Hence we use strip function to get rid of all this symbols.

5.We iterate through every word in line and check if its present in the list unique_word . if not then we append that word to the list and finally we print the list which will contain all unigue words from the file.

Generate a report that lists each individual word followed by the number of times it appears in the text.sort this new list based on the second tuple value and see which word appears the most frequently

filepath ='C:\\Users\\Preeti\\Desktop\\DOCSSS\\quiztext.txt'
frequency_word={}
with open(filepath,'r') as file:
for line in file:   
for word in line.split():
word=word.strip('!')
word=word.strip(',')
word=word.strip('.')
if word not in frequency_word:
frequency_word[word]=1
else:
frequency_word[word]+=1


a=frequency_word.items()
Frequency_list=list(a)
  
Frequency_list=sorted(Frequency_list,key=lambda x:x[1],reverse=True)
print(Frequency_list)

Explanation:

1.We create an empty dictionary named frequency_word.

2.We open the file in read mode using open function and pass the filepath to the function .

3.Using for loop, we read every line in file and then we read every word in the line using split function and pass space as the parameter to split i.e.split(" "), if comma was the parameter to split then we wpuld have used split(",").

4.we use strip function to get rid of all this symbols.

5.We iterate through every word in line and check if its present in the dictionary frequency_word . if not then we store the word as key and value as 1 using syntax dictionary[key]=value.

If the word present in the dictionary frequency_word then we increment the value of the dictionary key 'word' by 1.

6.Then we convert key and value of the dictionary to tuple using dictionary.items() .And store them in a variable which will be later used to convert it to ist using list function.

7.To sort the list based on second value of tuple we use sorted function and pass lambda function as key .

lambda function is defined as

lambda input : output

so here we give lambda x : x[1]

so list will be sroted based on second value of tuple.Also specify reverse=True if you want to sort the list in descending order else dont specify it.

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:...
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...
Write three to five sentences response to this post in your own words . RE: Sect....
Write three to five sentences response to this post in your own words . RE: Sect. 1 Week 15 DQ 13: A bare minimum of care In the additional readings there is a statement, "To assess these conflicts between professionalism and justice, I need to clarify the nature and scope of professional obligations,..... Where do professional obligations come from? How do professionals acquire them? How stringent are their demands?........special interest influence the answers and therefore does not fulfill justice." I...
Reply to the comment below. Do you agree with disagree with the statements. Something that caught...
Reply to the comment below. Do you agree with disagree with the statements. Something that caught my eye that I was not previously aware of was that the "Mexican Modern Art Movement" was not only based on Mexican sources, in terms of technique. The art has been influenced by European and Indian sources as well. The Spanish invasion caused the integration of the Indian's natural talent in the visual arts with European technique. I was surprised to find out that...
The story goes that Gyges was a shepherd in the service of the King. In a...
The story goes that Gyges was a shepherd in the service of the King. In a most unusual circumstance he came upon a dead man, removed the man's ring, and discovered that it made him invisible. He conspired to take the periodic report of the shepherds to the King -- once there he seduced the Queen and eventually took control of the Kingdom by conspiring with the Queen. Plato continues the story: "Suppose now that there were two such magic...
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 do it in Python Write the simplest program that will demonstrate iteration vs recursion using...
Please do it in Python Write the simplest program that will demonstrate iteration vs recursion using the following guidelines - Write two primary helper functions - one iterative (IsArrayPrimeIter) and one recursive (IsArrayPrimeRecur) - each of which Take the array and its size as input params and return a bool. Print out a message "Entering <function_name>" as the first statement of each function. Perform the code to test whether every element of the array is a Prime number. Print out...
A friend at work has lunch with you every day, Monday through Friday. This female friend...
A friend at work has lunch with you every day, Monday through Friday. This female friend has been dating a guy for about a year. They seem to be very much in love. He has been pushing for her to move in with him. Finally, he has bought her an engagement ring, and they hope to get married in a year . . . or two . . . or three. He has a lot of old debts he wants...
Open the Excel program In our last computer assignment we learned how to find the standard...
Open the Excel program In our last computer assignment we learned how to find the standard normal distribution up to the given score value a, that is we found P(Z < a). We used Excel instead of the standard normal distribution table and evaluated P(Z<-1.72) with the command =NORMDIST(1.72,B1,B2,TRUE) and we obtained 0.042716 approximately. Here Z is standard normal distribution. In this exercise we will learn how to go backwards, that is from the probability P(Z < a) to the...
please answer and explain Video Transcript: Promoting Children's Health: A Focus on Nutrition in Early Childhood...
please answer and explain Video Transcript: Promoting Children's Health: A Focus on Nutrition in Early Childhood Settings: >> Our most important job is to keep the children safe and healthy. And within keeping them healthy and keeping them safe, we want to make sure that they are receiving proper nutrition. So at this age, starting healthy habits, we want to make sure that the preschool and kindergarten age children are receiving all that we can give them when it comes...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT