frank
frank

Reputation: 3598

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

Upvotes: 7

Views: 9929

Answers (5)

s3nh
s3nh

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

kederrac
kederrac

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)))) 

enter image description here

And the performances: enter image description here

Upvotes: 0

ErikDM
ErikDM

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

Spark
Spark

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 :

enter image description here

Upvotes: 2

Rakesh
Rakesh

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

Related Questions