Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight specific words in a sentence in python

I have some text, and I want to highlight specific words. I wrote a script to loop through the words and highlight the desired text, but how do I set this up to return it to sentences?

from termcolor import colored

text = 'left foot right foot left foot right. Feet in the day, feet at night.'
l1 = ['foot', 'feet']
for t in text.lower().split():
    if t in l1:
        print(colored(t, 'white', 'on_red'))
    else: print(t)

In the above example, I want to end up with an output of two sentences, not a list of all the words, with relevant words highlighted

like image 376
frank Avatar asked Jan 27 '23 00:01

frank


2 Answers

Use str.join

Ex:

from termcolor import colored
text='left foot right foot left foot right. Feet in the day, feet at night.'
l1=['foot','feet']
result = " ".join(colored(t,'white','on_red') if t in l1 else t for t in text.lower().split())
print(result)
like image 143
Rakesh Avatar answered Jan 28 '23 15:01

Rakesh


You just need to have the entire words in a list and join then with space

from termcolor import colored
text='left foot right foot left foot right. Feet in the day, feet at night.'
l1=['foot','feet']
formattedText = []
for t in text.lower().split():
    if t in l1:
        formattedText.append(colored(t,'white','on_red'))
    else: 
        formattedText.append(t)

print(" ".join(formattedText))

Result below :

enter image description here

like image 39
Sundeep Pidugu Avatar answered Jan 28 '23 15:01

Sundeep Pidugu