I created a function in Python to highlight and output a specific word as follows. There is a [Code List](# Code List) at the end of the page.
This is all you need.
import re
First, create a dictionary to change the font color and background color.
This time, if " yellow "` `, <font background-color = # FFCC00> yellow background color </ font>, if` `" red "
, red characters I set it like </ font>.
color_dic = {'yellow':'\033[43m', 'red':'\033[31m', 'blue':'\033[34m', 'end':'\033[0m'}
Next, set the keyword you want to highlight. This time, I set the prefecture name as the keyword.
keyword = ["Tokyo", "Chiba", "Saitama", "Kanagawa Prefecture", ...]
The keywords set above will be searched in order with the for statement, but the order of the list becomes important here, because depending on the keyword, it may be a substring of another keyword. This is because it may be. For example, when searching for a city, ward, town, or village.
keyword = [... , "Tsu city", "大Tsu city", ...]
If, simply search for the word from the left and color the hits to get the following.
So the solution is to sort the words in the list in order of increasing number of characters. Then, "Otsu City" will be searched first, so the above problem will not occur. Below is the code.
#keyword = sorted(keyword, key=lambda x:len(x), reverse=True)
#You pointed out a better way to write in the comments.
keyword.sort(key=len, reverse=True)
Finally, create a function that receives the output text, keywords, and color specification information, and outputs it.
def print_hl(text, keyword, color="yellow"):
for kw in keyword:
bef = kw
aft = color_dic[color] + kw + color_dic["end"]
text = re.sub(bef, aft, text)
print(text)
The execution example is as follows.
text = "I live in tokyo"
print_hl(text, keyword)
that's all!
import re
color_dic = {'yellow':'\033[43m', 'red':'\033[31m', 'blue':'\033[34m', 'end':'\033[0m'}
def print_hl(text, keyword, color="yellow"):
for kw in keyword:
bef = kw
aft = color_dic[color] + kw + color_dic["end"]
text = re.sub(bef, aft, text)
print(text)
keyword = ["Tokyo", "Chiba", "Saitama", "Kanagawa Prefecture"]
keyword.sort(key=len, reverse=True)
text = "I live in tokyo"
print_hl(text, keyword)
How to output colored output to the console
Recommended Posts