将句子中的键替换为其值

Cod*_*st 0 python dictionary key list key-value

我有一本字典和一个清单

dict1= {'good':'bad','happy':'sad','pro':'anti'}
Run Code Online (Sandbox Code Playgroud)
list1=['she is good','this is a product','they are pro choice']
Run Code Online (Sandbox Code Playgroud)
newlist=[]
for index, data in enumerate(list1):
    for key, value in dict1.items():
        if key in data:
            list1[index]=data.replace(key, dict1[key])
            newlist.append(list1[index])
Run Code Online (Sandbox Code Playgroud)
The output I get is
['she is bad','this is a antiduct','they are anti choice']

desired output is
['she is bad','this is a product','they are anti choice']
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?它也正在取代产品的专业版。我只希望它作为独立词存在时取代 pro。

Sam*_*ord 5

一种选择是对split每个短语进行替换,用get字典中的直号代替replace

>>> dict1= {'good':'bad','happy':'sad','pro':'anti'}
>>> list1={'she is good','this is a product','they are pro choice'}
>>> [' '.join(dict1.get(word, word) for word in phrase.split()) for phrase in list1]
['this is a product', 'she is bad', 'they are anti choice']
Run Code Online (Sandbox Code Playgroud)

请注意,这不会保留短语中的空格,也不会很好地处理标点符号。 re并且itertools.groupby将是处理那些更复杂的情况的有用工具。