python - 正则表达式解析 python 中的导入语句

标签 python regex

有人可以帮我编写单个正则表达式以从 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/

相关文章:

python - Google 文档 API 和 Python : How to change the owner of a document?

python - 根据条件删除 Pandas 组

java - 在Java中使用正则表达式实现简单的字符串匹配

python - findall 的完整表达式

java - 正则表达式包含一个或多个电话号码

regex - 使用 sed 捕获的组变量作为 bash 命令的输入

python - 测试由于浮点限制而导致的舍入误差

python - SQLALchemy 访问列对象

python - 如何检查 numpy.float64(0)?

来自 Visual Studio 2013 兼容性的 C++ Regex