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
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)
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 :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With