python - 为字符串解析 ~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
解决方案
如果您只打开文件一次并将所有行保存到fileContent
中,在适当的地方添加break
,并重新使用匹配项来访问捕获group
的 s,您将获得类似这样的内容(print
3.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
推荐阅读
- powershell - 使用 Powershell 将项目符号点格式化为 Outlook 正文
- c# - 在网格外的控件中显示大型历史字段
- python - 熊猫计算每一行与前行的总和
- windows - 如何使用批处理文件将多个文件夹压缩成一个 rar 存档文件?
- python - Python:用 ssh 连接替换 shell 管道
- sql - 有 17 个子查询 case 语句,有更好的方法吗?
- javascript - 带有 MVC5 AjaxBeginForm 的 Jquery Noty 插件
- mysql - 如何在另一个api的基础上管理第一个api的回滚事务
- java - Akka Streams 丢弃消息?
- java - 在 Jetty servlet 中处理 uri 参数