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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
179 次 |
| 最近记录: |