Question

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:


Output the full text of the file


Output the number of words in the file


Output the number of sentences in the file


Output the first sentence in the file


Output the last sentence in the file


Output the length of the first sentence


Output the length of the last sentence


Prepare two files for submission. The first file should be a text file containing your Python solution. The second file should contain your output.

mod7.txt is below

I do not come here as an advocate, because whatever position the suffrage movement may occupy in the United States of America, in England it has passed beyond the realm of advocacy and it has entered into the sphere of practical politics. It has become the subject of revolution and civil war, and so tonight I am not here to advocate woman suffrage. American suffragists can do that very well for themselves. I am here as a soldier who has temporarily left the field of battle in order to explain - it seems strange it should have to be explained, what civil war is like when civil war is waged by women. I am not only here as a soldier temporarily absent from the field at battle; I am here, and that, I think, is the strangest part of my coming, I am here as a person who, according to the law courts of my country, it has been decided, is of no value to the community at all; and I am adjudged because of my life to be a dangerous person, under sentence of penal servitude in a convict prison. It is not at all difficult if revolutionaries come to you from Russia, if they come to you from China, or from any other part of the world, if they are men. But since I am a woman it is necessary to explain why women have adopted revolutionary methods in order to win the rights of citizenship. We women, in trying to make our case clear, always have to make as part of our argument, and urge upon men in our audience the fact, a very simple fact, that women are human beings. Suppose the men of Hartford had a grievance, and they laid that grievance before their legislature, and the legislature obstinately refused to listen to them, or to remove their grievance, what would be the proper and the constitutional and the practical way of getting their grievance removed? Well, it is perfectly obvious at the next general election the men of Hartford would turn out that legislature and elect a new one. But let the men of Hartford imagine that they were not in the position of being voters at all, that they were governed without their consent being obtained, that the legislature turned an absolutely deaf ear to their demands, what would the men of Hartford do then? They couldn't vote the legislature out. They would have to choose; they would have to make a choice of two evils: they would either have to submit indefinitely to an unjust state of affairs, or they would have to rise up and adopt some of the antiquated means by which men in the past got their grievances remedied. Your forefathers decided that they must have representation for taxation, many, many years ago. When they felt they couldn't wait any longer, when they laid all the arguments before an obstinate British government that they could think of, and when their arguments were absolutely disregarded, when every other means had failed, they began by the tea party at Boston, and they went on until they had won the independence of the United States of America. It is about eight years since the word militant was first used to describe what we were doing. It was not militant at all, except that it provoked militancy on the part of those who were opposed to it. When women asked questions in political meetings and failed to get answers, they were not doing anything militant. In Great Britain it is a custom, a time-honoured one, to ask questions of candidates for parliament and ask questions of members of the government. No man was ever put out of a public meeting for asking a question. The first people who were put out of a political meeting for asking questions, were women; they were brutally ill-used; they found themselves in jail before 24 hours had expired. We were called militant, and we were quite willing to accept the name. We were determined to press this question of the enfranchisement of women to the point where we were no longer to be ignored by the politicians. You have two babies very hungry and wanting to be fed. One baby is a patient baby, and waits indefinitely until its mother is ready to feed it. The other baby is an impatient baby and cries lustily, screams and kicks and makes everybody unpleasant until it is fed. Well, we know perfectly well which baby is attended to first. That is the whole history of politics. You have to make more noise than anybody else, you have to make yourself more obtrusive than anybody else, you have to fill all the papers more than anybody else, in fact you have to be there all the time and see that they do not snow you under. When you have warfare things happen; people suffer; the noncombatants suffer as well as the combatants. And so it happens in civil war. When your forefathers threw the tea into Boston Harbour, a good many women had to go without their tea. It has always seemed to me an extraordinary thing that you did not follow it up by throwing the whiskey overboard; you sacrificed the women; and there is a good deal of warfare for which men take a great deal of glorification which has involved more practical sacrifice on women than it has on any man. It always has been so. The grievances of those who have got power, the influence of those who have got power commands a great deal of attention; but the wrongs and the grievances of those people who have no power at all are apt to be absolutely ignored. That is the history of humanity right from the beginning. Well, in our civil war people have suffered, but you cannot make omelettes without breaking eggs; you cannot have civil war without damage to something. The great thing is to see that no more damage is done than is absolutely necessary, that you do just as much as will arouse enough feeling to bring about peace, to bring about an honourable peace for the combatants; and that is what we have been doing. We entirely prevented stockbrokers in London from telegraphing to stockbrokers in Glasgow and vice versa: for one whole day telegraphic communication was entirely stopped. I am not going to tell you how it was done. I am not going to tell you how the women got to the mains and cut the wires; but it was done. It was done, and it was proved to the authorities that weak women, suffrage women, as we are supposed to be, had enough ingenuity to create a situation of that kind. Now, I ask you, if women can do that, is there any limit to what we can do except the limit we put upon ourselves? If you are dealing with an industrial revolution, if you get the men and women of one class rising up against the men and women of another class, you can locate the difficulty; if there is a great industrial strike, you know exactly where the violence is and how the warfare is going to be waged; but in our war against the government you can't locate it. We wear no mark; we belong to every class; we permeate every class of the community from the highest to the lowest; and so you see in the woman's civil war the dear men of my country are discovering it is absolutely impossible to deal with it: you cannot locate it, and you cannot stop it. "Put them in prison," they said, "that will stop it." But it didn't stop it at all: instead of the women giving it up, more women did it, and more and more and more women did it until there were 300 women at a time, who had not broken a single law, only "made a nuisance of themselves" as the politicians say. Then they began to legislate. The British government has passed more stringent laws to deal with this agitation than it ever found necessary during all the history of political agitation in my country. They were able to deal with the revolutionaries of the Chartists' time; they were able to deal with the trades union agitation; they were able to deal with the revolutionaries later on when the Reform Acts were passed: but the ordinary law has not sufficed to curb insurgent women. They had to dip back into the middle ages to find a means of repressing the women in revolt. They have said to us, government rests upon force, the women haven't force, so they must submit. Well, we are showing them that government does not rest upon force at all: it rests upon consent. As long as women consent to be unjustly governed, they can be, but directly women say: "We withhold our consent, we will not be governed any longer so long as that government is unjust." Not by the forces of civil war can you govern the very weakest woman. You can kill that woman, but she escapes you then; you cannot govern her. No power on earth can govern a human being, however feeble, who withholds his or her consent. When they put us in prison at first, simply for taking petitions, we submitted; we allowed them to dress us in prison clothes; we allowed them to put us in solitary confinement; we allowed them to put us amongst the most degraded of criminals; we learned of some of the appalling evils of our so-called civilisation that we could not have learned in any other way. It was valuable experience, and we were glad to get it. I have seen men smile when they heard the words "hunger strike", and yet I think there are very few men today who would be prepared to adopt a "hunger strike" for any cause. It is only people who feel an intolerable sense of oppression who would adopt a means of that kind. It means you refuse food until you are at death's door, and then the authorities have to choose between letting you die, and letting you go; and then they let the women go. Now, that went on so long that the government felt that they were unable to cope. It was [then] that, to the shame of the British government, they set the example to authorities all over the world of feeding sane, resisting human beings by force. There may be doctors in this meeting: if so, they know it is one thing to feed by force an insane person; but it is quite another thing to feed a sane, resisting human being who resists with every nerve and with every fibre of her body the indignity and the outrage of forcible feeding. Now, that was done in England, and the government thought they had crushed us. But they found that it did not quell the agitation, that more and more women came in and even passed that terrible ordeal, and they were obliged to let them go. Then came the legislation - the "Cat and Mouse Act". The home secretary said: "Give me the power to let these women go when they are at death's door, and leave them at liberty under license until they have recovered their health again and then bring them back." It was passed to repress the agitation, to make the women yield - because that is what it has really come to, ladies and gentlemen. It has come to a battle between the women and the government as to who shall yield first, whether they will yield and give us the vote, or whether we will give up our agitation. Well, they little know what women are. Women are very slow to rouse, but once they are aroused, once they are determined, nothing on earth and nothing in heaven will make women give way; it is impossible. And so this "Cat and Mouse Act" which is being used against women today has failed. There are women lying at death's door, recovering enough strength to undergo operations who have not given in and won't give in, and who will be prepared, as soon as they get up from their sick beds, to go on as before. There are women who are being carried from their sick beds on stretchers into meetings. They are too weak to speak, but they go amongst their fellow workers just to show that their spirits are unquenched, and that their spirit is alive, and they mean to go on as long as life lasts. Now, I want to say to you who think women cannot succeed, we have brought the government of England to this position, that it has to face this alternative: either women are to be killed or women are to have the vote. I ask American men in this meeting, what would you say if in your state you were faced with that alternative, that you must either kill them or give them their citizenship? Well, there is only one answer to that alternative, there is only one way out - you must give those women the vote. You won your freedom in America when you had the revolution, by bloodshed, by sacrificing human life. You won the civil war by the sacrifice of human life when you decided to emancipate the negro. You have left it to women in your land, the men of all civilised countries have left it to women, to work out their own salvation. That is the way in which we women of England are doing. Human life for us is sacred, but we say if any life is to be sacrificed it shall be ours; we won't do it ourselves, but we will put the enemy in the position where they will have to choose between giving us freedom or giving us death. So here am I. I come in the intervals of prison appearance. I come after having been four times imprisoned under the "Cat and Mouse Act", probably going back to be rearrested as soon as I set my foot on British soil. I come to ask you to help to win this fight. If we win it, this hardest of all fights, then, to be sure, in the future it is going to be made easier for women all over the world to win their fight when their time comes.

Homework Answers

Answer #1
import sys


sys.stdout = open('output.txt', 'w') #putting the output shown on the console to the output.txt file

def sentence(fname): #function to fetch first and last lines and their length
    with open(fname, "r") as file: #opening the input file

        first_sentence = file.readline() # fetching the first line

        last_sentence = "" #variable for last sentence
        for line in file: #iterating through input file
            last_sentence = line
        print(last_sentence) #printng last sentence

    # printing first sentence
    print("First_sentence :\n" + first_sentence)
    first_length = len(first_sentence.split()) #fetchin length of first sentence
    print("Length of first sentence is :", str(first_length)+"\n")

    # printing last sentence
    print("Last_sentence : \n " + last_sentence)
    last_length=len(last_sentence.split()) #fetchin length of last sentence
    print("Length of last sentence is :", str(last_length)+"\n")



def word_lines(file_name): #function to count words and lines

    # declaring variables for storing no of words and lines
    num_words = 0
    num_lines = 0

    #reading through input file
    with open(file_name, 'r') as f:

        # iterating in each sentences for every count of words
        for sentence in f:
            num_lines += 1 #increament of no of lines
            word = 'Y'
            for letter in sentence:
                if (letter != ' ' and word == 'Y'):
                    num_words += 1
                    word = 'N'

                elif (letter == ' '):
                    word = 'Y'


    # prints the no of words
    print("No. of words present: ", num_words)

    # prints the no of lines
    print("No of lines present: ", num_lines)




#Calling through main function
if __name__ == '__main__':  #Using Main function
    file_name = 'mod7.txt'  #Declaring variable of input file
    try:
        word_lines(file_name) #calling function for lines and word fetching
        sentence(file_name) #calling method for sentence fetching
    except:
        print('File not found') #for exceptions

Provided mod7.txt Text file : It is only adjusting itself in one line.

Output File: Required Output is showing below. Since the provided text format is only adjusting itself in a single format, that's why number of lines are showing 1.

Summary : This python program reads the input text file named as mod7.txt and fetches the details output of the text content, no of words in text, no of lines in text, first sentence, last sentence, length of first and last sentences and saves all the outputs to an output file named as Ouput.txt as asked in the question. This program would work smooth on other txt files as well.

Provide the name of your files carefully, in case if throws directory error, check the directory and put it there carefully.

P.s. Hope you are satisfied with the provided solution, please give a thumbs up, Good Day !

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
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 a program in python reverse each and every word of the sentence using function taking...
Write a program in python reverse each and every word of the sentence using function taking string as input parameter from user and passing that string into function and also explain the logic ======================================= input: 'Exam is gonna be good' output: 'maxE si annog eb doog' ================ i am trying like this but getting confused '.'join([w::-1] for w in s.split()]) i need more focus on explanations because it is making me confuse i am not clear with concepts so please...
The following code to run as the described program on python. The extra test file isn't...
The following code to run as the described program on python. The extra test file isn't included here, assume it is a text file named "TXT" with a series of numbers for this purpose. In this lab you will need to take a test file Your program must include: Write a python program to open the test file provided. You will read in the numbers contained in the file and provide a total for the numbers as well as the...
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...
1. What are the requirements for successful price discrimination? Does this type of dry cleaning qualify?...
1. What are the requirements for successful price discrimination? Does this type of dry cleaning qualify? 2. What are other examples of price discrimination? 3. The effectiveness of price discrimination is a different question than whether businesses should be able to discriminate by price. Is this an issue that deserves regulation, or is it best left to the market? Why Women Pay More From dry cleaning to haircuts, women often pay more than men due to gender pricing. Find out...
As we learn more about the people who have come before us, we have to be...
As we learn more about the people who have come before us, we have to be careful not judge them through the lens of the present, or assume they could or should have acted as you or I today would act. Remember, "The past is a foreign country: they do things differently there." In that spirit, identify an American belief or practice we generally understand or accept today as "normal" that, one hundred years from now, future generations might be...
In the previous Module (Investment Tools) we were given the cash flows and the discount rates,...
In the previous Module (Investment Tools) we were given the cash flows and the discount rates, and we had to solve for IRR, NPV, MIRR, PayBack, or whatever In this Module, we have to figure out the cash flows for ourselves and put them through the tools of the last Module. But the rate we used was still given to us. So, while it is safe to assume that at some point before the end of the semester, we will...
Speaking Up in Meetings Barbara J. Krumsiek of the Calvert Group recently talked about the style...
Speaking Up in Meetings Barbara J. Krumsiek of the Calvert Group recently talked about the style of meetings that take place in her organization: I think it can be a little jarring actually for people who are used to perhaps a little more civility. I think we’re civil, but we’re direct. I don’t like meetings if my direct reports leave the room and turn to somebody and say, “Can you believe someone said that?” And so I try to explain...
1. In the reading, Marmot compares the life expectancy and average income of men in Costa...
1. In the reading, Marmot compares the life expectancy and average income of men in Costa Rica to that of Black men in the United States. This suggests to him that: absolute deprivation alone cannot explain health disparities health outcomes like life expetancy can be entirely explained by diffrences in income income is a better predictor of health than social position all groups in the U.S. derive a "health bonus" from living in the U.S. 2. In the Whitehall Study,...
Python #Write a function called are_anagrams. The function should #have two parameters, a pair of strings....
Python #Write a function called are_anagrams. The function should #have two parameters, a pair of strings. The function should #return True if the strings are anagrams of one another, #False if they are not. # #Two strings are considered anagrams if they have only the #same letters, as well as the same count of each letter. For #this problem, you should ignore spaces and capitalization. # #So, for us: "Elvis" and "Lives" would be considered #anagrams. So would "Eleven plus...