2016-03-01 121 views
1

我正在为一个单词搜索文本文件。它找到该单词并返回包含该单词的行。这很好,但我想在该行中突出显示或使该单词粗体。如何“突出显示”文本文件中找到的单词?

我可以在Python中执行此操作吗?另外我可以使用更好的方式来获取用户的txt文件路径。特殊字符

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 
+0

你是什么意思突出行?你的意思是保存一个新文件,并突出显示该行。打印它突出显示?突出显示一个文本编辑器?还有别的吗?我猜你的意思是保存一个新文件,并突出显示该行,但这取决于你想保存的文件格式。 .RTF? HTML吗? .DOC?还有别的吗? – DJMcMayhem

+0

我很抱歉将文件保存为.txt,并突出显示搜索到的单词。 – jeffkrop

+0

.txt用于纯文本,没有highliting。 – DJMcMayhem

回答

8

一种格式是\033[(NUMBER)(NUMBER);(NUMBER)(NUMBER);...m

第一数目可以是0,1,2,3,或4。对于颜色,我们只使用3和4 3表示前景颜色和4代表背景颜色。第二个数字是颜色:

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

因此,要打印“Hello World!”具有蓝色背景和黄色前景,我们可以做到以下几点:

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

每当你开始一个颜色,你将要重置为默认值。这就是\033[m所做的。

注意:这只适用于控制台。您无法在纯文本文件中着色文本。这就是为什么它被称为明文文字。

+1

考虑到问题下面的注释,您应该确定这将在控制台中提供彩色输出(只要终端支持它)。 –

+0

@ColinPitrat:谢谢。我改变了它。 – zondo

0

你可以使用Python的string.replace方法针对此问题:

#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)` 
0

我认为,你的意思是亮点是印刷用不同颜色的文本。不能保存的文字用不同的颜色(除非您可以用HTML或类似的东西)

与@zondo你应该得到这样的(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") 

使用HTML的一个例子是:

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") 

然后用.html结尾的文件将被创建,你可以用你的导航仪打开它。你的话会以红色突出显示! (这是一个非常基本的代码)

快乐黑客行为

+0

我使用了第一个代码,但是当我使用** shell **时,它不工作,我该怎么办? –