Skip to main content
 首页 » 编程设计

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

2025年05月04日15shihaiming

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

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

这是我的;

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。

请您参考如下方法:

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

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)