下面的代码工作正常,直到我添加正则表达式行。当我发表评论时,代码再次起作用......我很难过。我只使用正则表达式同时搜索文件中的三种不同类型的字符串(ascii,hex,string)。感谢任何帮助,谢谢!
elif searchType =='2':
print " Directory to be searched: c:\Python27 "
directory = os.path.join("c:\\","Python27")
userstring = raw_input("Enter a string name to search: ")
userStrHEX = userstring.encode('hex')
userStrASCII = ' '.join(str(ord(char)) for char in userstring)
regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) )
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(os.path.join(root, file))
for line in f.readlines():
#if userstring in line:
if regex.search(line):
print "file: " + os.path.join(root,file)
break
else:
print "String NOT Found!"
break
f.close()
答案 0 :(得分:4)
当我运行此代码时,出现了类似
的错误File "search.py", line 7
for root,dirname, files in os.walk(directory):
^
SyntaxError: invalid syntax
这是因为前一行包含已编译的正则表达式,缺少右括号:
regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) )
应该阅读
regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) ) )