Skip to main content
 首页 » 编程设计

python之用re解析python文件

2025年05月04日27Free-Thinker

我有一个 python 文件作为

test.py  
 
import os 
class test(): 
 
    def __init__(self): 
        pass 
 
    def add(num1, num2): 
        return num1+num2 

我正在以字符串形式读取此文件:

with open('test.py', 'r') as myfile: 
    data=myfile.read() 
 
print data 

现在,我的数据包含包含所有行和新行的字符串。 我需要找到带有 start of class 和 def 的行。

例如:

我需要将输出打印为:

class test(): 
def __init__(self): 
def add(num1, num2): 

我如何使用正则表达式处理它?<​​/p>

请您参考如下方法:

如果您想遵循正则表达式方法,请使用

re.findall(r'(?m)^[ \t]*((?:class|def)[ \t].*)', data) 

或

re.findall(r'^[ \t]*((?:class|def)[ \t].*)', data, flags=re.M) 

参见 regex demo

重点是您应该使用 ^ 作为 line anchor 的开头(因此,(?m) 在开头或re.M 标志是必需的),然后匹配水平空格(使用 [\t]),然后是 class 或 def (使用 (?:class|def)),然后是空格或制表符,然后是换行符以外的 0+ 个字符 (.*)。

如果您还计划处理 Unicode 空格,则需要将 [\t] 替换为 [^\S\r\n\f\v](并且使用 re.UNICODE 标志)。

Python demo :

import re 
p = re.compile(r'^[ \t]*((?:class|def)[ \t].*)', re.MULTILINE) 
s = "test.py \n\nimport os\nclass test():\n\n    def __init__(self):\n        pass\n\n    def add(num1, num2):\n        return num1+num2" 
print(p.findall(s)) 
# => ['class test():', 'def __init__(self):', 'def add(num1, num2):']