Question

Define a function called divideSentences in the python file. This function will take in one input...

Define a function called divideSentences in the python file. This function will take in one input argument: a string. This string will typically be a whole piece of text, a paragraph or more. This function will separate the text into sentences, assuming that each sentence ends with either a period, a question mark, or an exclamation mark. It should return a list of the sentence strings. Be sure that the sentence-ending mark is still attached to the sentence. Remove any trailing “whitespace” from the front or end of each sentence.

Hints and suggestions:

  • There are many different ways to approach this question. Various string methods might be useful, or you can just loop over the characters in the input string. Keep it simple, and be willing to try different approaches.

  • Simplistic use of the split method won’t work, because splitting the input string on the end-of-sentence symbols will remove them, but there could be ways of making split work if you’re clever.

  • Use one or more accumulator variables: one for the list of strings, and potentially another for the current sentence string.

use the test code below to test

def test_divideSentences():
    """Tests for the divideSentences function."""
    print("--------------------------------------")
    print("Testing divideSentences:")
    allOk = True

    s1 = "A phrase, not a sentence"
    r1 = divideSentences(s1)

    if r1 != ['A phrase, not a sentence']:
        print('Called: divideSentences(', s1, ')')
        print("Expected: ['A phrase, not a sentence']   but function returned: ", r1)
        allOk = False

    s2 = "The red hen ate the worm. I ran to the door. Why is the hen red? I don't know!"
    r2 = divideSentences(s2)

    if r2 != ['The red hen ate the worm.', 'I ran to the door.', 'Why is the hen red?', "I don't know!"]:
        print('Called: divideSentences(', s2, ')')
        print("Expected:",
              ['The red hen ate the worm.', 'I ran to the door.', 'Why is the hen red?', "I don't know!"],
              "but function returned: ", r2)
        allOk = False

    s3 = '''Atticus said to Jem one day, "I'd rather you shot at tin cans in the backyard, but I know you'll go after birds. Shoot all the blue jays you want, if you can hit 'em, but remember it'screen a sin to kill a mockingbird." That was the only time I ever heard Atticus say it was a sin to do something, and I asked Miss Maudie about it. "Your father'screen right," she said. "Mockingbirds don't do one thing except make music for us to enjoy. They don't eat up people'screen gardens, don't nest in corn cribs, they don't do one thing but sing their hearts out for us. That'screen why it'screen a sin to kill a mockingbird."'''
    r3 = divideSentences(s3)

    if r3 != [
        'Atticus said to Jem one day, "I\'d rather you shot at tin cans in the backyard, but I know you\'ll go after birds.',
        "Shoot all the blue jays you want, if you can hit 'em, but remember it'screen a sin to kill a mockingbird.",
        '" That was the only time I ever heard Atticus say it was a sin to do something, and I asked Miss Maudie about it.',
        '"Your father\'screen right," she said.',
        '"Mockingbirds don\'t do one thing except make music for us to enjoy.',
        "They don't eat up people'screen gardens, don't nest in corn cribs, they don't do one thing but sing their hearts out for us.",
        "That'screen why it'screen a sin to kill a mockingbird.", '"']:
        print('Called: divideSentences(', s3, ')')
        print('Expected:', [
            'Atticus said to Jem one day, "I\'d rather you shot at tin cans in the backyard, but I know you\'ll go after birds.',
            "Shoot all the blue jays you want, if you can hit 'em, but remember it'screen a sin to kill a mockingbird.",
            '" That was the only time I ever heard Atticus say it was a sin to do something, and I asked Miss Maudie about it.',
            '"Your father\'screen right," she said.',
            '"Mockingbirds don\'t do one thing except make music for us to enjoy.',
            "They don't eat up people'screen gardens, don't nest in corn cribs, they don't do one thing but sing their hearts out for us.",
            "That'screen why it'screen a sin to kill a mockingbird.", '"'],
              "but function returned: ", r3)
        allOk = False

    s4 = "I ran! The ghost followed me. Where could I hide? Could I escape it? It howled after me, crying, 'Wait, you dropped your wallet!' What?"
    r4 = divideSentences(s4)

    if r4 != ['I ran!', 'The ghost followed me.', 'Where could I hide?', 'Could I escape it?',
              "It howled after me, crying, 'Wait, you dropped your wallet!", "' What?"]:
        print('Called: divideSentences(', s4, ')')
        print("Expected:", ['I ran!', 'The ghost followed me.', 'Where could I hide?', 'Could I escape it?',
                            "It howled after me, crying, 'Wait, you dropped your wallet!", "' What?"],
              'but function returned: ', r4)
        allOk = False

    print()
    if allOk:
        print("divideSentences PASSESD ALL TESTS!")
    else:
        print("divideSentences FAILED ONE OR MORE TEST!")
    print("--------------------------------------")
    input("Press a key to go on: ")

Homework Answers

Answer #1

Python Program:

def divideSentences(inputStr):
""" Function that accepts a string argument and returns the list of sentence strings """
# List that holds the sentences
sentences = []
start=0
# Iterating over sentence
for i in range(len(inputStr)):
# Checking for Period, Question Mark, Exclamation
if inputStr[i]=='.' or inputStr[i]=='?' or inputStr[i]=='!':
# Extracting sentence
sentence = inputStr[start:i+1]
# Stripping whitespace from left side
sentence = sentence.lstrip()
# Stripping whitespace from right side
sentence = sentence.rstrip()
# Adding to list
sentences.append(sentence)
# Changing start value
start = i+1
# Returning the list
return sentences
  
# Example Text
text = "Lorem ipsum dolor sit amet! consectetuer adipiscing elit? sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam. quis nostrud exercitation ulliam corper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem veleum iriure dolor in hendrerit in vulputate velit esse molestie consequat! vel willum lunombro dolore? eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi."

# Calling function
resList = divideSentences(text)
# Printing result
print(resList)

___________________________________________________________________________________________

Code Screenshot:

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 Python, Write a function to return all the common characters in two input strings. The...
Using Python, Write a function to return all the common characters in two input strings. The return must be a list of characters and only unique characters will be returned. For example, given 'abcdefg' and 'define', the function will return ['d', 'e', 'f'] (note e only appears once). (Hint: Use the in operator.) Following is what I've done so far. When I enter 'abcdefg' for the first string, and 'define' for the second string, I get ['d','e','f'], which is correct....
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...
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:...
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first,...
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first, third, fifth (and so on) characters of the strings, with each character both preceded and followed by the ^ symbol, and with a newline appearing after the last ^ symbol. The function returns no value; its goal is to print its output, but not to return it. Q2) Write a Python function called lines_of_code that takes a Path object as a parameter, which is...
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...
Adding large numbers with linked list Requirement - in C++ - use file for the input...
Adding large numbers with linked list Requirement - in C++ - use file for the input (nums.txt) - (recommended) use only one linked list to hold intermediate answer and final answer. You may use another one to reverse the answer. - store the num reversely in the linked list. For example, the num 123 is stored as 3 (at first node), 2 (at second node) and 1 (at third node) in the linked list. - write a function that performs...
Instructions​: You will find a file named findingNemo.m and another named nemo.txt. The first contains code...
Instructions​: You will find a file named findingNemo.m and another named nemo.txt. The first contains code which will read in strings from nemo.txt, then call Lab08(string) on each line of nemo.txt. Your job is to write Lab08.m. The Lab08 function will take in a string as input and will return an integer n as output. The value of n will be the nth word in the input string, where n is the location of the substring 'Nemo'. Please note that...
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...
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...
There are two reflective essays from MED students during their third year internal medicine clerkship. One...
There are two reflective essays from MED students during their third year internal medicine clerkship. One student sees each connection to a patient as like the individual brush strokes of an artist and the other sees gratitude in a patient with an incurable illness and is moved to gratitude in her own life. (WORD COUNT 500) Reflect on both essays and then choose one and describe how the student grew from the experience. Then explain what you learned as a...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT