0

我有以下程序,它在某个位置的行中搜索字符串,然后输出搜索匹配。我希望能够选择是否在搜索中忽略大小写并在输出行中突出显示搜索字符串。

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   

我怎样才能使这项工作适用于“是”的情况?

4

1 回答 1

1

该问题与您在re.sub通话中进行的字符串连接有关。如果是编译的正则表达式对象而不是字符串,则表达式无效Fore.YELLOW + find + Fore.RESETfind

为了解决这个问题,我建议对正则表达式模式使用与原始字符串不同的变量名:

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

然后pattern作为第一个参数传递给re.sub. find在所有情况下都将保持为字符串,因此它将在第二个参数的表达式中起作用:

line = re.sub(pattern, Fore.YELLOW + find + Fore.RESET, line)
于 2013-10-04T10:07:32.197 回答