有人可以帮我编写单个正则表达式以从 python 源代码行获取模块吗?
from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz
它有3个子部分
[from(\s)<module>(\s)] --> get module if this part exist
import(\s)<module> --> get module
[(\s)as(\s)<alias>] --> ignore if this part exist
像这样
:?[from(\s)<module>(\s)]import(\s)<module>:?[(\s)as(\s)<alias>]
最佳答案
不使用正则表达式,使用内置的 python 库 ast 可能是更好的方法。 https://docs.python.org/2/library/ast.html您可以使用它来解析 python 语法。
import ast
import_string = """from abc.lmn import pqr
from abc.lmn import pqr as xyz
import abc
import abc as xyz"""
modules = []
for node in ast.iter_child_nodes(ast.parse(import_string)):
if isinstance(node, ast.ImportFrom):
if not node.names[0].asname: # excluding the 'as' part of import
modules.append(node.module)
elif isinstance(node, ast.Import): # excluding the 'as' part of import
if not node.names[0].asname:
modules.append(node.names[0].name)
这会给你 ['abc.lmn', 'abc'] 如果你想提取其他信息,调整起来相当容易。
关于python - 正则表达式解析 python 中的导入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44988487/