【发布时间】:2021-02-01 04:05:02
【问题描述】:
我有一本字典如下:
dict_ = {
'the school in USA' : 'some_text_1',
'school' : 'some_text_1',
'the holy church in brisbane' : 'some_text_2',
'holy church' : 'some_text_2'
}
还有一个句子列表如下:
text_sent = ["Ram is going to the holy church in brisbane",\
"John is going to holy church", \
"shena is going to the school in USA", \
"Jennifer is going to the school"]
我想用 text_sent 中的相应值替换出现的 dict_ 字典键。我这样做如下:
for ind, text in enumerate(text_sent) :
for iterator in dict_.keys() :
if iterator in text :
text_sent[ind] = re.sub(iterator, dict_[iterator], text)
for i in text_sent:
print(i)
我得到的输出如下:
Ram is going to the some_text_2 in brisbane
John is going to some_text_2
shena is going to the some_text_1 in USA
Jennifer is going to the some_text_1
预期输出是:
Ram is going to some_text_2
John is going to some_text_2
shena is going to some_text_1
Jennifer is going to some_text_1
我需要的是,较长的字符串(例如,“布里斯班的圣堂”)需要替换,以防万一,句子中没有完整的字符串, 只有这样才能使用较小的版本(例如,'holy church')而不是较长的版本来替换 text_sent 句子中的相应值。
【问题讨论】:
标签: python string list dictionary