python 字符串查找(高亮顯示找到的內容)

 test.conf 是準備被查找的文件,ontest.py是要執行查詢的文件,要放在同級目錄下。

 

 ontest.py內容如下:

# --查找高亮顯示自定義函數(file_name文件名,inquiry_content要查找的內容)
def fetch(file_name, inquiry_content):
    with open(file_name, 'r', encoding="utf-8") as read_f:
        for readLine in read_f:
            temp = readLine.rstrip()  # 去掉右邊的空格符和回車符
            # 通過加背景顏色標記出查找到的字符串
            print(temp.replace(inquiry_content, '\033[1:44m%s\033[0m' % inquiry_content))
    read_f.close()


fetch('test.conf', 'a')

運行效果如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章