Reputation: 3598
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
Upvotes: 7
Views: 9929
Reputation: 556
In my opinion, you could split your sentence before loop, and try instruction as below.
ic = text.lower().split()
for ix, el in enumerate(ic):
if el in list_of_words:
# Run your instructions
ic[ix] = colored(el,'white','on_red'), end=" "
Second sentence will be then:
output = ' '.join(ic)
Upvotes: 1
Reputation: 17322
to have a better speed than @Rakesh suggested solution I will recommend to use:
from functools import reduce
from itertools import chain
text = 'left foot right foot left foot right. Feet in the day, feet at night.'
l1 = ['foot','feet']
print(reduce(lambda t, x: t.replace(*x), chain([text.lower()], ((t, colored(t,'white','on_red')) for t in l1))))
Upvotes: 0
Reputation: 78
You can also use end=" "
inside print() to make everything a sentence.
Example:
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'), end=" ")
else: print(t, end=" ")
print("\n")
Upvotes: 1
Reputation: 2487
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 :
Upvotes: 2
Reputation: 82765
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)
Upvotes: 6