Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bold searched text that is contained in a string with Python

Example If the user searches "car" I would like the output to look like

Find your favorite car today, car sale for next 2 days.

Notice that car is bolded. Google does it: enter image description here

What's the best way to go about doing this in Python? The bolding is in HTML.

like image 394
Glenn Dayton Avatar asked Mar 12 '26 00:03

Glenn Dayton


2 Answers

>>> the_string = "New Cars, Used Cars, Car Reviews, Car Finance Advice - Cars.com"
>>> re.sub(r'(car)', r'<b>\1</b>', the_string, flags=re.I)
'New <b>Car</b>s, Used <b>Car</b>s, <b>Car</b> Reviews, <b>Car</b> Finance Advice - <b>Car</b>s.com'

It's a little bit tricky to figure out exactly what should count as an instance of "car", though; this would make "cartoon" and so on. You could try \b(cars?)\b for this specific phrase; in general, you might want to use a stemmer.

like image 159
Danica Avatar answered Mar 15 '26 01:03

Danica


>>> import re
>>> the_string = "New Cars, Used Cars, Car Reviews, Car Finance Advice - Cars.com"
>>> word = 'cars'
>>> toreplace = "<span class='highlight' STYLE='color:black'>\g<0></span>"
>>> pattern = re.compile(re.escape(word), re.I)
>>> highlighted_txt = re.sub(pattern,toreplace,the_string)
>>> highlighted_txt
 "New <span class='highlight' STYLE='color:black'>Cars</span>, Used <span class='highlight' STYLE='color:black'>Cars</span>, Car Reviews, Car Finance Advice - <span class='highlight' STYLE='color:black'>Cars</span>.com"
>>>
like image 38
Rakesh Avatar answered Mar 15 '26 02:03

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!