2016-03-01 123 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 **時,它不工作,我該怎麼辦? –