[Python] Change the text color and background color of a specific keyword in print output

Purpose of this article

I created a function in Python to highlight and output a specific word as follows. image.png There is a [Code List](# Code List) at the end of the page.

Commentary

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. image.png

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)

image.png

that's all!

Code list

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)

reference

How to output colored output to the console

Recommended Posts

[Python] Change the text color and background color of a specific keyword in print output
[Python scraping] Output the URL and title of the site containing a specific keyword to a text file
Output in the form of a python array
Change the saturation and brightness of color specifications like # ff000 in python 2.5
Change the standard output destination to a file in Python
Get the number of specific elements in a python list
Detect objects of a specific color and size with Python
Read the standard output of a subprocess line by line in Python
Open an Excel file in Python and color the map of Japan
Output the number of CPU cores in Python
Get the caller of a function in Python
Make a copy of the list in Python
Change the color of Fabric errors and warnings
A discussion of the strengths and weaknesses of Python
How to count the number of elements in Django and output to a template
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
Fill the background with a single color with OpenCV2 + Python
A reminder about the implementation of recommendations in Python
Automate background removal for the latest portraits in a directory with Python and API
Get the value of a specific key in a list from the dictionary type in the list with Python
The result of making a map album of Italy honeymoon in Python and sharing it
[Machine learning] "Abnormality detection and change detection" Let's draw the figure of Chapter 1 in Python.
[Mac] A super-easy way to execute system commands in Python and output the results
[Sublime Text 2] Always execute a specific file in the project
Sort and output the elements in the list as elements and multiples in Python.
[Note] Import of a file in the parent directory in Python
[Tips] Problems and solutions in the development of python + kivy
Find the eigenvalues of a real symmetric matrix in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
Specify the encoding of the unicode string in the Python 2.x print statement
The story of Python and the story of NaN
Count the number of Thai and Arabic characters well in Python
How to determine the existence of a selenium element in Python
Change the background of Ubuntu (GNOME)
Color extraction with Python + OpenCV solved the mystery of the green background
How to change the color of just the button pressed in Tkinter
[Introduction to Python] How to output a character string in a Print statement
How to check the memory size of a variable in Python
Output the contents of ~ .xlsx in the folder to HTML with Python
Feel free to change the label of the legend in Seaborn in python
How to check the memory size of a dictionary in Python
Change the Python version of Homebrew
A function that measures the processing time of a method in python
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
Export and output files in Python
Reading and writing text in Python
Get the title and delivery date of Yahoo! News in Python
The story of creating a bot that displays active members in a specific channel of slack with python
Get the number of readers of a treatise on Mendeley in Python
Get the list in the S3 bucket with Python and search with a specific Key. Output the Key name, last update date, and count number to a file.
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
Set up a dummy SMTP server in Python and check the operation of sending from Action Mailer
How to input a character string in Python and output it as it is or in the opposite direction.
Get a capture of the entire web page in Selenium Python VBA
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
If you want a singleton in python, think of the module as a singleton
Graph of the history of the number of layers of deep learning and the change in accuracy
python> does not include the letters mm> if "mm" not in text: / print "not including mm"
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Check the in-memory bytes of a floating point number float in Python