首页 > 解决方案 > 如何检查列表中是否存在字典值并替换

问题描述

nounphrase = ['At the same time, other ncp1 arose, such as computers made by DEC, ncp2 , mainly 
               for use by businesses.']

res_dict = {'rep_sentence': 'At the same time, other ncp1 arose, such as computers made by DEC, 
                             ncp2 , mainly for use by businesses',
            'replacements': [{'replacedPhrase': 'desktop systems and workstations',
                              'replacement': 'ncp1'},
                             {'replacedPhrase': 'Sun, and SGI', 'replacement': 'ncp2'}]}

for each_rep in res_dict['replacements']:
    res = [masked_nounphrase for masked_nounphrase in noun_phrase if each_rep['replacement'] in 
            masked_nounphrase]
    final_result = [sub.replace(each_rep['replacement'],each_rep['replacedPhrase']) for sub in 
                    res] 
    print(final_result)

我想检查 res_dict 值ncp1ncp2在 nounphrase 中,如果找到,将其替换为 replacePhrase 键。使用上面的代码片段,我只能替换一个键,并且我得到以下答案:

['At the same time, other desktop systems and workstations arose, such as computers made by DEC, ncp2 , mainly for use by businesses.']

标签: python-3.x

解决方案


一种方法是,str使用 list 的修改值更新noun_phrase

s = ''
for elem in res_dict['replacements']:
    s = "".join([x.replace(elem['replacement'], elem['replacedPhrase']) if elem['replacement'] in x else x for x in noun_phrase])
    noun_phrase = [s]
print(s)  

输出:

At the same time, other desktop systems and workstations arose, such as computers made by DEC, Sun, and SGI , mainly for use by businesses. 

推荐阅读