Skip to main content
 首页 » 编程设计

Python之使用正则表达式从文件中获取变量

2024年10月24日42oomusou

问题

给定一个文件,例如:

#Example 
x = 'foo = {}' 
 
bar = { 
  'color': 'blue' 
} 
 
print('Hello World') 

使用正则表达式,程序会找到对应于字典或set literals的变量名并打印出来。上面的输出只是:

bar 

像这样的一行

yes = { "no={}" } 

应该只返回是。


变量可以用\w+? expression 我只是不确定从哪里开始。

当前代码

for line in open('program.txt'): 
   array = line.split(' ') 
 
   for item in array: 
      if '{' in item: 
         print(array[0]) 

这仅适用于基本示例,并且存在一些问题。同一行上的多变量也不起作用。它也不使用正则表达式。

请您参考如下方法:

你可以这样做,

>>> s = '''#Example 
x = 'foo = {}' 
 
bar = { 
  'color': 'blue' 
} 
 
print('Hello World') 
yes = { "no={}" }''' 
>>> re.findall(r'^\s*(\w+)\s*=\s*\{[^}]*\}', s, re.M) 
['bar', 'yes'] 

或

>>> [i for i in re.findall(r'\{(?:\{[^{}]*\}|[^{}])*\}|^\s*(\w+)\s*=\s*(?=\{)', s, re.M) if i] 
['bar', 'yes'] 
>>>  

如果你想把它定义为一个函数,你可以使用下面的。

def check(s): 
    return [i for i in re.findall(r'\{(?:\{[^{}]*\}|[^{}])*\}|^\s*(\w+)\s*=\s*(?=\{)', s, re.M) if i]