我有以下程序,它在某个位置的行中搜索字符串,然后输出搜索匹配。我希望能够选择是否在搜索中忽略大小写并在输出行中突出显示搜索字符串。
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
我怎样才能使这项工作适用于“是”的情况?