我有以下程序在某個位置搜索一行字符串,然後輸出搜索匹配。我希望能夠選擇是否在搜索中忽略大小寫,並突出顯示輸出行中的搜索字符串。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」的情況?
你重新定義你的變量'find'的正則表達式時不區分大小寫的答案是肯定的。在那裏查看你的if-else情況:'find - re.compile ...''find'find = find'。雖然這是一個非常多餘的陳述,但它確實保留了'find'字符串,這個字符串是早先放入的。 – Evert