如何在第一场比赛后继续下一个文件 - Python 3.x

时间:2016-05-16 14:45:09

标签: python-3.x match pycharm

我目前正在使用此代码:

from bs4 import BeautifulSoup
import glob
import os
import re
import contextlib


@contextlib.contextmanager
def stdout2file(fname):
    import sys
    f = open(fname, 'w')
    sys.stdout = f
    yield
    sys.stdout = sys.__stdout__
    f.close()


def trade_spider():
    os.chdir(r"C:\Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            with open(file, encoding="utf8") as f:
                contents = f.read()
                soup = BeautifulSoup(contents, "html.parser")
                for item in soup.findAll("ix:nonfraction"):
                    if re.match(".*AuditFeesExpenses", item['name']):
                        print(file.split(os.path.sep)[-1], end="| ")
                        print(item['name'], end="| ")
                        print(item.get_text())
trade_spider()

它的作用如下: - 打开文本文件 - 搜索给定目录中的所有.html文件 - 如果RegEx匹配 - >将结果打印到指定的文本文件

在每个html文件中,最多包含我的RegEx的两个字符串。这意味着有时我每个文件都有两个结果。我现在要做的是告诉Python它应该继续自动到下一个文件 IF RegEx找到了一个匹配(否匹配很好,因为如果python没有找到匹配项,它已经自动进入下一个文件。

所以我的结果应该没有匹配(如果没问题)或者一个匹配,而不是继续下一个文件而不将第二个字符串与我的RegEX匹配。

你们有人可以帮助我吗?是否有任何简短而优雅的魔法可以插入到我的代码中而不会过多地改变它?

任何帮助表示赞赏!

P.S。我已经搜索了stackflow,因为匹配问题是一个非常受欢迎的问题,但我无法找到任何与我的问题相符的问题。如果我错过了关于这个主题的一些相关问题,对不起,如果你能发布相关链接,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试在最里面的break添加if

if re.match(".*AuditFeesExpenses", item['name']):
    print(file.split(os.path.sep)[-1], end="| ")
    print(item['name'], end="| ")
    print(item.get_text())
    break

现在,只要没有匹配,最里面的for就会继续。如果匹配,则进入if块并在突发后执行。

评论它是否适合您。