2013-10-04 24 views
0

我有以下程序在某個位置搜索一行字符串,然後輸出搜索匹配。我希望能夠選擇是否在搜索中忽略大小寫,並突出顯示輸出行中的搜索字符串。Python re.sub不能與colorama和re.compile一起工作

import re, os, glob 
from colorama import init, Fore, Back, Style 
init(autoreset=True) 

path = "c:\\temp2" 
os.chdir(path) 

def get_str(msg): 
    myinput = input(msg) 
    while True: 
     if not bool(myinput): 
      myinput = input('No Input..\nDo it again\n-->') 
      continue 
     else: 
      return myinput 

ext = get_str('Search the files with the following extension...') 
find = get_str('Search string...') 
case = get_str(' Ignore case of search string? (y/n)...') 
print() 

if case == "y" or case == "Y": 
    find = re.compile(find, re.I) 
else: 
    find = find 

files_to_search = glob.glob('*.' + ext) 

for f in files_to_search: 
    input_file = os.path.join(path, f) 
    with open(input_file) as fi: 
     file_list = fi.read().splitlines() 
     for line in file_list: 
      if re.search(find, line): 
       line = re.sub(find, Fore.YELLOW + find + Fore.RESET, line) 
       print(f, "--", line) 

如果我選擇「n」的情況下,該程序的作品。在程序運行時,如果我選擇「Y」我得到這個錯誤:

Search the files with the following extension...txt 
Search string...this 
    Ignore case of search string? (y/n)...y 

Traceback (most recent call last): 
    File "C:\7. apps\eclipse\1. workspace\learning\scratch\scratchy.py", line 36, in <module> 
    line = re.sub(find, Fore.YELLOW + find + Fore.RESET, line) 
TypeError: Can't convert '_sre.SRE_Pattern' object to str implicitly 

我怎樣才能使這項工作爲「yes」的情況?

+0

你重新定義你的變量'find'的正則表達式時不區分大小寫的答案是肯定的。在那裏查看你的if-else情況:'find - re.compile ...''find'find = find'。雖然這是一個非常多餘的陳述,但它確實保留了'find'字符串,這個字符串是早先放入的。 – Evert

回答

1

該問題與您在調用re.sub時所進行的字符串連接有關。如果find是編譯的正則表達式對象而不是字符串,則表達式Fore.YELLOW + find + Fore.RESET無效。

爲了解決這個問題,我建議使用不同的變量名正則表達式模式比你用原來的字符串:

if case == "y" or case == "Y": 
    pattern = re.compile(find, re.I) 
else: 
    pattern = find 

然後通過pattern作爲第一個參數re.subfind將保持在所有情況下的字符串,所以它會在表達工作,第二個參數:

line = re.sub(pattern, Fore.YELLOW + find + Fore.RESET, line) 
+0

即將完成。還必須將搜索更改爲'if re.search(pat,line):' –