python-3.x - 如何检查列表中是否存在字典值并替换
问题描述
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 值ncp1
并ncp2
在 nounphrase 中,如果找到,将其替换为 replacePhrase 键。使用上面的代码片段,我只能替换一个键,并且我得到以下答案:
['At the same time, other desktop systems and workstations arose, such as computers made by DEC, ncp2 , mainly for use by businesses.']
解决方案
一种方法是,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.
推荐阅读
- apache-kafka - 如何通过 OpenLiberty 上的 JMS 连接到 Kafka?
- apache-spark - Spark shuffle 因 AccessDenied 异常而失败
- flutter - 如何使用颤振提供者监听列表中的变化?
- arrays - 通过 JSONB 数组在 Rails erb 中渲染 each_with_index 循环会导致重复
- codenameone - 无需下载即可获取 URL 的文件大小
- ansible - 处理程序未从 Ansible 中的角色调用
- c++ - 运行自定义 Makefile 时出现未定义的引用错误
- django - TemplateDoesNotExist :在 Django 上未检测到模板
- angular - 单击添加按钮时带有自动完成显示的角材料芯片列表
- ansible - 是否可以在任务中为角色定义变量?