Search code examples
pythoninputsentence

Creating a dictionary of three word phrases based on input


def splitSentence(sentence):
    dictionarySentence = {}
    setence_split = sentence.split()
    three_word_list = [' '.join(setence_split[i:i+3]) for i in range(0, len(setence_split), 3)]
    #grouped_words = [' '.join(words[i: i + 3]) for i in range(0, len(words), 3)]
    for key,char in enumerate(three_word_list):
        {
            dictionaryTweets.update({char:1})
            
        }
    return dictionaryTweets
    return three_word_list
splitSentence("My name is Allen. How are you?")

Output:

{'My name is': 1, 'Allen. How are': 1, 'you?': 1}

Output looking for:

{'My name is': 1, 'is Allen. How': 1, 'How are you?': 1}

The output should be a dictionary whose keys are all three word phrases based on a sentence inputted into the function. I am not 100% how you would ensure that the phrases are three words long. Could someone assist with this?


Solution

    1. Function name and definitions are different.
    2. You cannot have 2 return statements.
    3. dictionaryTweets is not defined.

    The below code is working fine.

    def splitTextToTriplet(sentence):
        dictionaryTweets = {}
        three_word_list = []
        setence_split = sentence.split()
        for i in range(0,len(setence_split)-1,2):
            three_word_list.append(' '.join(setence_split[i:i+3]))
        for key, char in enumerate(three_word_list):
                dictionaryTweets.update({char: 1})
    
        return dictionaryTweets, three_word_list
    
    print(splitTextToTriplet("My name is Allen. How are you?"))