我们假设搜索字词为xxx car costs
,我有一段this is a xxx brand new car, it costs around $120000
我想在段落
中的匹配单词周围插入<strong>
标记
我尝试了什么
search = 'xxx car costs'
content = 'this is a xxx brand new car, it costs around $120000'
search_terms = search.split()
for word in search_terms:
if word not in content: continue
print('<strong>{}</strong>'.format(word))
这给了我来自段落的匹配关键字:: xxx 汽车 费用
预期结果:这是 xxx 全新汽车,费用 $ 120000
答案 0 :(得分:1)
使用str.replace
的简单方法:
for word in search_terms:
content = content.replace(word, '<strong>'+word+'</strong>')
答案 1 :(得分:1)
相反,它有点清洁imho:
search = 'xxx car costs'
content = 'this is a xxx brand new car, it costs around $120000'
search_terms = search.split()
new_content = content
for word in search_terms:
new_content = new_content.replace(word, '<strong>%s</strong>' % word)
print new_content