2013-10-04 25 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):' –