在下面的代码中,程序从用户那里获取字符串数据并将其转换为 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!!!"
最佳答案
伙计们,我认为 user706808 想要搜索文件中所有出现的搜索字符串,并且:
- 如果在文件中找到字符串,则每次出现,然后在每行的基础上,打印 lineno,文件路径名
- 如果在文件中找不到字符串,则在每个文件的基础上打印文件路径名(但不是内容)和搜索字符串。 最简单的方法是保留一个 bool 值(或整数)跟踪事件(nMatches),然后在关闭文件或路径名脱离上下文之前在最后打印 no-match-message(如果 nMatches 为 0 或 False) .
你能确认一下吗?假设这就是你想要的, 您需要做的就是拆分这一大行代码...
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'。)
关于python - 未找到打印搜索的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6424949/