搜索正在打印结果,并且显示“未找到字符串”。状况

发布于 2024-11-15 23:34:29 字数 1084 浏览 0 评论 0原文

有人可以向我解释为什么我的条件搜索语句返回两个结果(它找到字符串并将结果打印到屏幕上,并打印“未找到字符串”)。我已经做出了改变,但我一定忽略了一些事情。

代码:

 if choice == '1':
         regex2  = re.compile(r'\s+')
         for root,dirname, files in os.walk(directory):
             for file2 in files:
                 if file2.endswith(".log") or file2.endswith(".txt"):
                    f=open(os.path.join(root, file2))
                    for i,line in enumerate(f.readlines()):
                        result2 = regex.search(re.sub(regex2, '',line))
                        if result2:
                           ln = str(i)
                           print "\nLine: " + ln
                           print "File: " + os.path.join(root,file2)
                           print "String Type: " + result2.group() + '\n'
                           temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')

                    else:
                       print "String not found!!!"
                    break  
                    f.close()    
         re.purge()

Can someone explain to me why my conditional search statement is returning both results (it finds the string and prints the results to the screen and it prints "String Not Found"). I've made changes, but I must be overlooking something.

Code:

 if choice == '1':
         regex2  = re.compile(r'\s+')
         for root,dirname, files in os.walk(directory):
             for file2 in files:
                 if file2.endswith(".log") or file2.endswith(".txt"):
                    f=open(os.path.join(root, file2))
                    for i,line in enumerate(f.readlines()):
                        result2 = regex.search(re.sub(regex2, '',line))
                        if result2:
                           ln = str(i)
                           print "\nLine: " + ln
                           print "File: " + os.path.join(root,file2)
                           print "String Type: " + result2.group() + '\n'
                           temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')

                    else:
                       print "String not found!!!"
                    break  
                    f.close()    
         re.purge()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挖个坑埋了你 2024-11-22 23:34:29

我认为你有一个缩进问题:

...
for i,line in enumerate(f.readlines()):
    result2 = regex.search(re.sub(regex2, '',line))
    if result2:
        ln = str(i)
        print "\nLine: " + ln
        print "File: " + os.path.join(root,file2)
        print "String Type: " + result2.group() + '\n'
        temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')

    else:  # <<<<<<<<<<<<<<<<<<<< HERE !!!!
        print "String not found!!!"
break
...

You have an indentation problem i think you want:

...
for i,line in enumerate(f.readlines()):
    result2 = regex.search(re.sub(regex2, '',line))
    if result2:
        ln = str(i)
        print "\nLine: " + ln
        print "File: " + os.path.join(root,file2)
        print "String Type: " + result2.group() + '\n'
        temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')

    else:  # <<<<<<<<<<<<<<<<<<<< HERE !!!!
        print "String not found!!!"
break
...
弥枳 2024-11-22 23:34:29

如果循环退出是因为它迭代的可迭代对象耗尽,而不是由于 break 语句,则执行 for 循环的 else 子句。由于您的循环不包含任何 break,因此 else 子句将始终被执行。

这是重构代码的尝试。它使用生成器函数来生成文件名列表,并使用 fileinput 模块来负责打开和关闭文件。由于 f.close() 之前的 break,您的 cod 从未显式关闭任何文件。

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)

The else clause to a for loop is execute if the loop exits because the iterable it iterates over is exhausted, rather than due to a break statement. Since your loop doesn't include any break, the else clause will always be executed.

Here is an attempt at refactoring your code. It uses a generator function to generate the list of filenames and the fileinput module to take care of opening and closing the files. Your cod never explicitly closes any file due to the break immediatley before f.close().

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)
缱绻入梦 2024-11-22 23:34:29

请稍微重构一下你的代码 - 有太多的缩进和混合控制结构。通过这种方式可以更容易地发现和纠正问题。

例如 - 将循环分为遍历和检查:

def look_through(directory):
    found = 0
    for root, dirname, files in os.walk(directory):
        for filename in files:
            result = process_file(root, filename)
            if result is not None:
                found += 1
                yield result
    if found == 0:
        print 'blah, not found'

def process_file(...

您现在看到之前代码的问题了吗?任何条件仅针对每个文件进行检查,然后再次针对每个目录进行检查。没有全局结果计数器或记录的搜索状态。

Please refactor your code a bit - there's way too much indentation and mixing control structures. It will be easier to both spot and correct the problem this way.

For example - split the loop into traversing and checking:

def look_through(directory):
    found = 0
    for root, dirname, files in os.walk(directory):
        for filename in files:
            result = process_file(root, filename)
            if result is not None:
                found += 1
                yield result
    if found == 0:
        print 'blah, not found'

def process_file(...

Do you see the problem with previous code now? Any condition was only checked per-file and then again - per-directory. There was no global counter of results, or search state recorded.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文