【问题标题】:Conditional writing and parsing of files (if elif else)文件的条件写入和解析(if elif else)
【发布时间】:2020-01-05 16:04:00
【问题描述】:

我想解析一些文件并将任何匹配项附加到字典中。 - 我的正则表达式确实有效,所以这里没有错误... 文件包含一些不同的公式,我需要检查不同的正则表达式 - 我无法手动执行此操作,因为我的文件夹中有超过 10.000 个文件。

无论如何,我想看看我的正则表达式是否匹配。如果是这样,我想将解析后的文件写入一个也可以工作的dict-,但是如果我的正则表达式 none 匹配,我想查看相应的文件名..(附加到列表)..

我的问题:我不知道如何相应地组合 if、elif 和 else 语句。所以应该是这样的:

  1. 打开文件并检查第一个正则表达式
  2. 如果正则表达式匹配追加到字典
  3. 如果正则表达式不匹配,请尝试第二个正则表达式
  4. 如果正则表达式匹配写入字典
  5. 如果我的正则表达式都不匹配写入文件到列表 -- 最后一步是让我检查配方

所以我阅读并尝试了:

files = ['C:/Users/file1.txt','C:/Users/file2.txt']
reg1 = r"some regex"
reg2 = r"some regex2"

error_list = []
dict_result = {}
for file in files:
  with open(file,'r', encoding='utf-8') as in_file:     
        content = in_file.read().lower()
        if re.match(reg1, content, re.IGNORECASE | re.DOTALL | re.MULTILINE):
            matches_reg1 = re.findall(reg1, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
            result = max(matches_reg1, key=len)
            result = str(result).replace('\n', '')
            dict_result["result"] = result
        elif re.match(reg2, content, re.IGNORECASE | re.DOTALL | re.MULTILINE):
            matches_reg2 = re.findall(reg2, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
            result = max(matches_reg2, key=len)
            result = str(result).replace('\n', '')
            dict_result["result"] = result
        else:
            error_list.append(file)
            print("ERROR: ", file)

但这绝对行不通.. 做得更好的是这个..但它似乎效率低下并且没有显示错误文件,只是第一个正则表达式的错误文件:

for file in files:

  with open(file,'r', encoding='utf-8') as in_file:     
        content = in_file.read().lower()
        matches_reg1 = re.findall(reg1, content, re.IGNORECASE | re.DOTALL | re.MULTILINE) 
        matches_reg2 = re.findall(reg2, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)

                if matches_reg1:
                    result = max(matches_reg1, key=len)
                    result = str(result).replace('\n', '')
                    dict_result["result"] = result
                if matches_reg2:

                    result = max(matches_reg2, key=len)
                    result = str(result).replace('\n', '')
                    dict_result["result"] = result
                else:
                    error_list.append(file)
                    print("ERROR: ", file)

...有人可以解释一种有效的方法来解决这个问题吗?如果我有一个不同正则表达式方法的列表,并且喜欢检查每个正则表达式直到匹配,否则将文件路径写入列表以供进一步分析..

也试过了..

matches_reg1 = re.findall(reg1,..)
if matches_reg1:
    ...
elif matches_reg1:
    match = re.findall(reg2, ...)

【问题讨论】:

  • 第一个代码以什么方式“绝对不起作用”?
  • 您的代码缺少一些对象,例如 namefiles 的值。
  • 第一个代码只显示了else 语句...虽然,我知道第一个正则表达式应该匹配一些文件

标签: python regex python-3.x if-statement conditional-statements


【解决方案1】:

如果没有更多详细信息,您的问题很难回答:您能提供文件的内容吗?否则,这是基于我对您的意图的理解的通用答案:调试代码的关键是 re.match 不返回布尔值,而是返回 None (如果不匹配)或 SRE_Match 对象(第一场比赛,包括它的位置)。

所以我建议你重写你的代码如下并设置断点来查看matches_reg1matches_reg2中捕获的内容。

content = in_file.read().lower()
matches_reg1 = re.match(reg1, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
if matches_reg1:
    # do whatever you like here (i copied your original code)
    all_matches_reg1 = re.findall(reg1, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
    result = max(all_matches_reg1, key=len)
    result = str(result).replace('\n', '')
    n_file.write(result)
else:
    matches_reg2 = re.match(reg2, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
    if matches_reg2:
        # do whatever you like here (i copied your original code)
        all_matches_reg2 = re.findall(reg2, content, re.IGNORECASE | re.DOTALL | re.MULTILINE)
        result = max(all_matches_reg2, key=len)
        result = str(result).replace('\n', '')
        n_file.write(result)
    else:
        # do whatever you like here (i copied your original code)
        error_list.append(name)
        print("ERROR: ", name)

编辑:您还可以在单​​个正则表达式中将所有正则表达式与“或”符号 (|) 结合起来,这样您就有了一个 if。要做到这一点并能够消除歧义,您需要询问“匹配”对象与哪个组匹配。例如,如果您有两个表达式来匹配“bli”和“bla”,您可以像这样匹配两者:

res = re.match("(bli)|(bla)", "blahbla")

然后你可以这样做:

if res:
    # lets get the details of the matched expressions
    res_gr = res.groups()

    # act according to which group matched
    if res_gr[0]:
        # first expression matched
        ...
    elif res_gr[1]:
        # second expression matched
        ...
    else:
        raise Exception("should not happen")
else:
    # no match at all

作为一个额外的提示,我强烈建议使用https://regex101.com/ 首先在 python 之外调试正则表达式。

【讨论】:

  • 谢谢,这就是我想要的。有没有一种有效的方法来检查不同正则表达式的列表? (如您在上面看到的,我简化了我的代码以进行说明)
  • 您还可以使用带有“或”符号的单个正则表达式 (|),这样您就有了一个 if。我相应地编辑了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 2011-08-19
  • 1970-01-01
  • 2014-03-09
  • 2011-08-15
  • 2017-05-03
相关资源
最近更新 更多