Reputation: 147
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
Upvotes: 6
Views: 36088
Reputation: 20336
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.
Upvotes: 16
Reputation:
I think that what you mean by highlight is printing the text with a different color. You can not save text with a different color (unless you be using html or something like that)
With the answer provided by @zondo you should get some code like this (python3)
import os
file_path = input("Enter the file path: ")
while not os.path.exists(file_path):
file_path = input("The path does not exists, enter again the file path: ")
with open(file_path, mode='rt', encoding='utf-8') as f:
text = f.read()
search_word = input("Enter the word you want to search:")
if search_word in text:
print()
print(text.replace(search_word, '\033[44;33m{}\033[m'.format(search_word)))
else:
print("The word is not in the text")
An example of using html, would be:
if search_word in text:
with open(file_path+'.html', mode='wt', encoding='utf-8') as f:
f.write(text.replace(search_word, '<span style="color: red">{}</span>'.format(search_word)))
else:
print("The word is not in the text")
Then a file ending with .html
will be created and you can open it with your navigator. Your word will be highlighted in red! (That's a really basic code)
happy hacking
Upvotes: 3
Reputation: 4007
You could use Pythons string.replace
method for this problem:
#Read in the a file
with file = open('file.txt', 'r') :
filedata = file.read()
#Replace 'the_word' with * 'the_word' * -> "highlight" it
filedata.replace(the_word, "*" + the_word + '*')
#Write the file back
with file = open('file.txt', 'w') :
file.write(filedata)`
Upvotes: 1