Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "highlight" a word found in a text file?

Tags:

python

I am searching a text file for a word. It finds the word and returns the line that has the word. This is good, but I would like to highlight or make the word bold in that line.

Can I do this in Python? Also I could use a better way to get the users txt file path.

def read_file(file):
    #reads in the file and print the lines that have searched word. 
    file_name = raw_input("Enter the .txt file path: ")
    with open(file_name) as f:
        the_word = raw_input("Enter the word you are searching for: ")
        print ""
        for line in f:
            if the_word in line:
                print line 
like image 823
jeffkrop Avatar asked Mar 01 '16 19:03

jeffkrop


Video Answer


1 Answers

Note: This will work only in the console. You cannot color text in a plaintext file. That is why it is called plaintext.

One format for special characters is \033[(NUMBER)(NUMBER);(NUMBER)(NUMBER);...m

The first number can be 0, 1, 2, 3, or 4. For colors, we use only 3 and 4. 3 means foreground color, and 4 means background color. The second number is the color:

0 black
1 red
2 green
3 yellow
4 blue
5 magenta
6 cyan
7 white
9 default

Therefore, to print "Hello World!" with a blue background and a yellow foreground, we could do the following:

print("\033[44;33mHello World!\033[m")

Whenever you start a color, you will want to reset to the defaults. That is what \033[m does.

like image 153
zondo Avatar answered Oct 11 '22 13:10

zondo