Python 如何按特定模式对序列中的单词进行排序

Python 如何按特定模式对序列中的单词进行排序,python,Python,所以基本上我需要对第一个字符串中的单词进行排序,以匹配第二个字符串的顺序 def sort_string_by_specific_pattern(self, initial_string, expected_string): #Remove punctuation from strings initial_string = str(initial_string).translate(None, string.punctuation) expecte

所以基本上我需要对第一个字符串中的单词进行排序,以匹配第二个字符串的顺序

def sort_string_by_specific_pattern(self, initial_string, expected_string):
    #Remove punctuation from strings
    initial_string = str(initial_string).translate(None, 
           string.punctuation)
    expected_string = str(expected_string).translate(None, 
           string.punctuation)

    new_sorted_string = " "  #we need spaces between words

    # map sentences to integer location
    spitted = expected_string.split()
    d_map = {w: [i for i in range(len(spitted)) if spitted[i] == w]
                for w in set(spitted)}

    initial_string = initial_string.split()

    # sort by calculated location mapping
    extracted_sorted = sorted(initial_string, key=d_map.get)
    new_sorted_string = str(new_sorted_string.join(extracted_sorted))
    return [new_sorted_string, expected_string ]
例如:

initial_string= 'apple one and two apple'

expected_string= 'apple one and apple two'
我想使初始的\u字符串看起来与预期的\u字符串完全相同,但主要问题是重复的单词“apple”

到目前为止我所做的: 我有一个字典,它将预期字符串中的单词作为关键字保存,将字符串中单词位置的索引作为值保存

d_map= {'and': [2], 'one': [1], 'apple': [0, 4], 'two': [3]}
但是,当我通过这个字典对初始字符串进行排序时,
sorted(initial\u string,key=d\u map.get)
结果是:

`new_sorted_string= 'apple apple one and two'`
而不是

new_sorted_string= 'apple one and apple two'

当两个字符串中的单词不同时会发生什么?在这种情况下,你能举个例子吗?重复的单词有什么问题?您需要在已排序的字符串列表中只保留一个“苹果”吗?@RockyLi如果字符串中的单词不同,我不希望出现这种情况。@m.raynal重复单词的问题是,我希望根据第二个字符串对第一个字符串进行排序,并且我希望保留字符串中的两个“苹果”。我想使初始的\u字符串从-->'apple one and two apple'到-->'apple one and apple two'与预期的\u字符串完全相同。我能问一下为什么吗?如果单词不一样,您不想做任何事情,因此只需检查两个字符串之间的单词包是否相同,然后返回第二个字符串(如果相同)?当两个字符串中的单词不同时会发生什么情况?在这种情况下,你能举个例子吗?重复的单词有什么问题?您需要在已排序的字符串列表中只保留一个“苹果”吗?@RockyLi如果字符串中的单词不同,我不希望出现这种情况。@m.raynal重复单词的问题是,我希望根据第二个字符串对第一个字符串进行排序,并且我希望保留字符串中的两个“苹果”。我想使初始的\u字符串从-->'apple one and two apple'到-->'apple one and apple two'与预期的\u字符串完全相同。我能问一下为什么吗?如果单词不一样,您不想做任何事情,那么只需检查两个字符串之间的单词包是否相同,然后返回第二个字符串(如果相同)?