[英]style matching words in paragraphs python
lets suppose a search term be xxx car costs
and i have a paragraphs this is a xxx brand new car, it costs around $120000
让我们假设一个搜索词是
xxx car costs
,我有一个段落, this is a xxx brand new car, it costs around $120000
i want insert a <strong>
tag around the matching words in paragraphs 我想在段落中的匹配词周围插入一个
<strong>
标记
What i tried 我尝试了什么
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))
This gave me matching keyterms from paragraphs :: xxx car costs 这给了我从段落:: XXX 用车 成本匹配keyterms
The desired result : this is a xxx brand new car , it costs $120000 期望的结果:这是XXX品牌的新车 ,它的成本 $ 120000
A naive approach using str.replace
: 使用
str.replace
的幼稚方法:
for word in search_terms:
content = content.replace(word, '<strong>'+word+'</strong>')
How about this instead, it's slightly cleaner 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.