Search code examples
pythonpython-3.xunique

How to recreate a sentence from the list of unique words and the position


I am creating a program which recreates a sentence from it's unique words and the positions of them.

So far I have managed to collect the unique words and the positions of the original sentence.

Here's what I have;

dictionary = {}#Creates an empty dictionary
List=[]#Creates an empty list



def play():
    unique = []
    sentence = "The fat cat, sat on the brick wall. The fat dog sat on the stone wall."#The original sentence
    splitted = sentence.split()


    for char in splitted:
        if char not in unique:#Finds the unique words
            unique.append(char)

    print(unique)#Prints the unique words


    for i,j in enumerate(splitted, 1):#puts i in each number next to each word, and j next to all the words in splitted
        if j in dictionary:#If the word is in dictionary
            List.append(dictionary[j])#The list will append the words position
        else:#Otherwise
            dictionary[j]=i#The dictionary will append the word and the number next to it
            List.append(i)#And then the list will take the number from it

    print(List)#Prints the Positions of the original sentence



play()#Plays the main loop

What I am stuck on doing is finding a way of recreating the original sentence using the unique words and the positions of the original sentence. Any Ideas would be a great help.

I am using Python 3.


Solution

  • If you just want the unique words in a list and a second list containing the indices where the respective words occurred, you can do it like this:

    sentence = "I do not like sentences like this sentence"
    unique = list()
    idx = list()
    
    for word in sentence.split():
       if not word in unique:
          unique.append(word)
       i = unique.index(word)
       idx.append(i)
    
    s = "" # the reconstructed sentence
    for i in idx:
       s = s + unique[i] + " "
    
    print(s)