简体   繁体   中英

Coloring words based on text list using python

I got two text files d.txt containing paragraph text and phrase.txt containing multi worded phrases like State-of-the-art, counter productive, Fleet Dynamism and like some found in link below

https://en.wikipedia.org/wiki/List_of_buzzwords

I need to color font matching phrase in d.txt if it is found in phrase.txt

Efforts so far:

phrases = open("phrase.txt").readlines()
words = open("d.txt").read()

for phrase in phrases:
    all_words_found = False
    phrase_words = phrase.lower().split(" ")
    for word in phrase_words:
        if word in words:
            all_words_found = True
            break

    if all_words_found:
        print (phrase)

Expected output: 在此处输入图片说明

Please Help!

thanks for the help:

Update: to create html output

To change the code above to create html output add a tag around the word during replace rather than ansi. The example here will use a simple span tag

words = ["catch phrase", "codeword"]
phrase = "He said a catch phrase. And a codeword was written on a wall."

new_phrase = phrase
for word in words:
    new_phrase = new_phrase.replace(i, f'<span style="color:Red;">{word}</span>')
print(new_phrase) #Rather than printing, send this wherever you want it.

Solution for inline print

However, to answer your basic question, which is how to replace a set of words in a given paragraph with the same word in a different color, try using .replace() and ansi color escape codes. This will work if you want to print out the words in your python environment.

Here's a simple example of a way to turn certain words in a line of text red:

words = ["catch phrase", "codeword"]
phrase = "He said a catch phrase. And a codeword was written on a wall."

new_phrase = phrase
for i in words:
    new_phrase = new_phrase.replace(i, f'\033[91m{i}\033[0;0m')
print(new_phrase)

Here is another stackoverflow post which talks about ANSI escape codes and colors in python output: How to print colored text in Python? ANSI escape codes are a way to change the color of your output - google them to find more options/colors.

In this example here are the codes I used: First to change the color to red:

\033[91m

Afer setting the color, you also have to change it back or the rest of the output will also be that color:

\033[0;0m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM