我有一本字典和一個清單
dict1= {'good':'bad','happy':'sad','pro':'anti'}
list1=['she is good','this is a product','they are pro choice']
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])
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']
我該如何解決?它也正在取代 prodcut 的 pro。我只希望它作為獨立詞存在時替換 pro。
uj5u.com熱心網友回復:
一種選擇是對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']
請注意,這不會保留短語中的空格,也不會很好地處理標點符號。 re
并且itertools.groupby
將是處理那些更復雜的情況的有用工具。
uj5u.com熱心網友回復:
看起來像是帶有單詞邊界的正則運算式的一個很好的用例:
dict1 = {'good':'bad','happy':'sad','pro':'anti'}
list1 = ['she is good','this is a product','they are pro choice', 'skimming has a basic dimension - product']
import re
regex = fr'\b({"|".join(map(re.escape, dict1))})\b'
out = [re.sub(regex, lambda m: dict1[m.group()], s) for s in list1]
輸出:
['she is bad',
'this is a product',
'they are anti choice',
'skimming has a basic dimension - product']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504911.html