在下面的代码中,程序从用户获取字符串数据并将其转换为ascii和hex,并在特定目录中搜索所有.log和.txt文件中的字符串,包括普通字符串,十六进制和ascii值。程序打印行#,找到的字符串类型,以及找到字符串的文件路径。但是,如果找到该字符串,我不仅希望它打印文件,我还希望它打印文件以及在搜索但未找到的文件中搜索的路径和字符串。我是新手,所以请不要对问题的简单性感到沮丧。我还在学习。谢谢。代码如下:
elif searchType =='2':
print "\nDirectory to be searched: " + directory
print "\nFile result2.log will be created in: c:\Temp_log_files."
paths = "c:\\Temp_log_files\\result2.log"
temp = file(paths, "w")
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(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII )))
goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n")
def walk_dir(directory, extensions=""):
for path, dirs, files in os.walk(directory):
for name in files:
if name.endswith(extensions):
yield os.path.join(path, name)
whitespace = re.compile(r'\s+')
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
result = regex.search(whitespace.sub('', line))
if result:
template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
break
elif not result:
template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
print output
temp.write(output)
else:
print "There are no files in the directory!!!"
答案 0 :(得分:1)
伙计们,我认为user706808想要在文件中搜索所有出现的searchstring,并且:
你能证实吗?假设这就是你想要的, 所有你需要改变的是分割这个巨大的代码...
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
...成
for curPathname in walk_dir(directory, (".log", ".txt")):
nOccurrences = 0
for line in fileinput.input(curPathname):
result = regex.search(whitespace.sub('', line))
if result:
...
nOccurrences += 1 # ignores multiple matches on same line
# You don't need an 'elif not result' line, since that should happen on a per-file basis
# Only get here when we reach EOF
if (nOccurrences == 0):
NOW HERE print the "not found" message, for curPathname
# else you could print "found %d occurrences of %s in ..."
听起来不错?
顺便说一下,你现在可以简单地将fileinput.filename()称为'curPathname'。
(您也可以将功能抽象为函数find_occurrences(searchstring,pathname),它返回int或Boolean'nOccurrences'。)