如何从唯一单词和位置列表中重新创建句子

时间:2016-01-08 15:18:27

标签: python python-3.x unique

我正在创建一个程序,它根据它的独特单词和它们的位置重新创建一个句子。

到目前为止,我已设法收集原始句子的独特单词和位置。

这就是我所拥有的;

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

我坚持做的是找到一种方法,使用原始句子的独特单词和位置重新创建原始句子。任何想法都会有很大的帮助。

我使用的是Python 3。

1 个答案:

答案 0 :(得分:1)

如果你只想要一个列表中的唯一单词和第二个列表,其中包含各个单词出现的索引,你可以这样做:

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)