我有一段代码可以从一个单独的文件中检索字典的变量名。代码:
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
这正确地将 a
和 d
识别为字典,同时避免了 c
的棘手情况(有大括号但不是dict) 和 foo
(具有字典语法,但在字符串中)
关于python - 使用正则表达式排除引号内的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965943/