Search code examples
pythonlistsentence

Creating sentences by a function without using a package


Im currently writing a program that looks at a list and iterates through a groups the words into sentences but whenever i ran it, I got [] and im not 100% sure why. Here is my code for reading in the file, and creating the sentence and an attached snippet of the list.

def import_file(text_file):
    wordcounts = []
    with open(text_file, encoding = "utf-8") as f:
        pride_text = f.read()
        sentences = pride_text.split(" ")
        return sentences





def create_sentance(sentance):
    sentence_list=[]
    my_sentence=""
    for character in sentance:
        if character=='.' or character=='?' or character=='!':
            sentence_list.append(my_sentence) 
            my_sentence=""
        else:
            my_sentence=my_sentence + character
        return sentence_list

Preview of List Calling of my functions

pride=import_file("pride.txt")
pride=remove_abbreviations_and_punctuation(pride)
pride=create_sentance(pride)
print(pride)

Solution

  • Your return sentence_list is indented one further than it should be. After the first iteration of the for, should the else condition execute and not the if, then your function returns sentence_list which was initialized to [ ]. Either way, if sentence was 20 characters long, your for will only run once given where your return call is.

    Make the following change:

    def create_sentance(sentance):
        sentence_list=[]
        my_sentence=""
    
        for character in sentance:
            if character=='.' or character=='?' or character=='!':
                sentence_list.append(my_sentence) 
                my_sentence=""
            else:
                # do you not want this in 'sentence_list'?
                my_sentence=my_sentence + character 
        return sentence_list