Python Forum
comparing 2 lists and highlighting key elements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing 2 lists and highlighting key elements
#1
from colorama import Fore, init

init()

key_words = ['mystery', 'the', 'charge', 'pretends']
paragraph_split = ['the', 'desired', 'mystery', 'corners', 'the', 'differential', '.', 'the', 'back', 'pretends', 'to', 'be', 'the']


def highlight(word):
    if word in key_words:
        return Fore.RED + str(word)
    else:
        return str(word)


colored_paragraph = list(map(highlight, paragraph_split))
print (" ".join(colored_paragraph))
Essentially I want the code to go through each word in paragraph_split list and check whether the respective word exists in the paragraph_split list.

If it exists, I want to replace the word with red font and move on to the next word

Then I want to join the words in colored_paragraph list and print out as a sentence.

The output should have some words colored in red and others in normal colour.

I ran my code in cmd and it gives all output in red font rather than just the words in key_words.
Output:
the desired mystery corners the differential . the back pretends to be the


Then I added encode("utf-8") in the print statement so it becomes
print (" ".join(colored_paragraph).encode("utf-8"))
This gave me
Output:
b'\x1b[31mthe desired \x1b[31mmystery corners \x1b[31mthe differential . \x1b[31mthe back \x1b[31mpretends to be \x1b[31mthe'
The words were not printed in colors. Can someone help me on this please? Thanks
Reply


Messages In This Thread
comparing 2 lists and highlighting key elements - by kapilan15 - Jan-15-2019, 02:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Screenshotting website and highlighting clickable elements natew 0 1,432 Aug-13-2024, 08:38 PM
Last Post: natew

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020