首页 > 解决方案 > 为字符串解析 ~4k 文件(复杂条件)

问题描述

问题描述

有一组约 4000 个 Python 文件,其结构如下:

@ScriptInfo(number=3254,
            attibute=some_value,
            title="crawler for my website",
            some_other_key=some_value)

scenario_name = entity.get_script_by_title(title)

目标

目标是从ScriptInfo装饰器中获取标题的值(在这种情况下,它是“我的网站的爬虫”),但是有几个问题:

1) 没有命名包含标题的变量的规则。这就是为什么它可以是 title_name、my_title 等。参见示例:

@ScriptInfo(number=3254,
            attibute=some_value,
            my_title="crawler for my website",
            some_other_key=some_value)

scenario_name = entity.get_script_by_title(my_title)

2) @ScriptInfo 装饰器可能有两个以上的参数,因此从括号之间获取其内容以获取第二个参数的值不是一种选择

我的(非常天真的)解决方案

但是保持不变的代码是该scenario_name = entity.get_script_by_title(my_title)行。考虑到这一点,我想出了解决方案:

import re
title_variable_re = r"scenario_name\s?=\s?entity\.get_script_by_title\((.*)\)"
with open("python_file.py") as file:
    for line in file:
        if re.match(regexp, line):
            title_variable = re.match(title_variable_re, line).group(1)
title_re = title_variable  + r"\s?=\s\"(.*)\"?"
with open("python_file.py") as file:
    for line in file:
        if re.match(title_re, line):
            title_value = re.match(regexp, line).group(1)
print title_value 

此代码片段执行以下操作:

1) 遍历(参见第一个with open)脚本文件并获取带有title值的变量,因为由程序员来选择它的名称 2)再次遍历脚本文件(参见第二个with open)并获取标题的值

stackoverflow 系列的问题

有没有比遍历脚本文件两次更好更有效的方法来获取标题(my_title's、 's 等)的值?title_name

标签: pythonparsingtext-parsing

解决方案


如果您只打开文件一次并将所有行保存到fileContent中,在适当的地方添加break,并重新使用匹配项来访问捕获group的 s,您将获得类似这样的内容(print3.x 后面有括号,2.7 没有括号):

import re

title_value = None 

title_variable_re = r"scenario_name\s?=\s?entity\.get_script_by_title\((.*)\)"
with open("scenarioName.txt") as file:
    fileContent = list(file.read().split('\n'))
    title_variable = None
    for line in fileContent:
        m1 = re.match(title_variable_re, line)
        if m1:
            title_variable = m1.group(1)
            break
    title_re = r'\s*' + title_variable  + r'\s*=\s*"([^"]*)"[,)]?\s*'
    for line in fileContent:
        m2 = re.match(title_re, line)
        if m2:
            title_value = m2.group(1)
            break
print(title_value)

这是正则表达式中未排序的更改列表:

  • 在 之前留出空间title_variable,这就是它的r'\s*' +用途
  • 留出空间=
  • 在 in 的行尾允许逗号或结束圆括号title_re,这就是它的[,)]?用途
  • 在行尾留出一些空间

在以下文件作为输入进行测试时:

@ScriptInfo(number=3254,
        attibute=some_value,
        my_title="crawler for my website",
        some_other_key=some_value)

scenario_name = entity.get_script_by_title(my_title)

它产生以下输出:

crawler for my website

推荐阅读