python - 使用正则表达式排除引号内的案例

标签 python regex python-3.x

我有一段代码可以从一个单独的文件中检索字典的变量名。代码:

import re
f = open('file.py')
f = f.readlines()
for line in f:
  line = line.replace('\n', '')
  a = re.findall(r'(\w*) *= *{', line)
  a = ''.join(a)
  if a != '':
    print(a)

我遇到的问题是它返回一组引号内的匹配项。

例如:

"foo = {}" #will output 'foo', but i don't want it to be recognized.

它应该只对不在引号中的字典进行提取。但我不确定如何将其添加到正则表达式语句中。

当前语句适用于所有内容,除了它在引号内的字典中提取:

(\w*) *= *{

最佳答案

与其使用正则表达式解析另一个 python 文件,不如考虑使用 ast 模块,它会为您完成实际解释文本的所有繁重工作。有了语法树后,选择字典分配就变得相当简单。

例子:

#sample.py

a = {1:2, 3:4}
b = "foo = {4:8, 15:16}"
c = {1,2,3}

def f():
    d = {"Hello": "World"}

#main.py
import ast

with open("sample.py") as f:
    tree = ast.parse(f.read())

for node in ast.walk(tree):
    if isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):
        for target in node.targets:
            if isinstance(target, ast.Name):
                print target.id

结果:

a
d

这正确地将 ad 识别为字典,同时避免了 c 的棘手情况(有大括号但不是dict) 和 foo(具有字典语法,但在字符串中)

关于python - 使用正则表达式排除引号内的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965943/

相关文章:

python - pandas 从单列中删除重复项,同时保持剩余行完整

javascript - 使用转义正则表达式特殊字符进行测试时字符串相等性失败

.net - .NET 的替代 RegEx 引擎,支持递归

python-3.x - 在具有相同 ID 的行末尾添加 Pandas 值

python - 用于迭代 2 个列表的简单 for 循环

python - 如何从我们的应用程序在 google appengine 中使用的数据存储中删除行?

python - 匹配字符直到到达某些字符的正则表达式是什么?

Ruby RegEx 问题 text.gsub[^\W-], '' ) 失败

python-3.x - 需要使用 python 进行数据库连接的概述说明

python - LightGBM中的predict_proba()函数如何在内部工作?