【问题标题】:regex to parse import statements in python正则表达式解析python中的导入语句
【发布时间】:2017-07-08 16:43:03
【问题描述】:

有人可以帮我写 single 正则表达式以从 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 regex


【解决方案1】:

使用内置的 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'] 如果您想提取其他信息,调整起来相当容易。

【讨论】:

  • 如果您想查找不在顶层的导入语句,使用ast.walk 可能是个好主意。
  • 好主意
  • 很好的答案。但是,此代码无法捕获多个导入,例如“import a, b, c, d”。而不是仅仅使用 node.names[0],你应该遍历所有 node.names。
【解决方案2】:

看起来您可以将 from 设为可选,而 import
同时忽略 as

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)[ ]*$

https://regex101.com/r/fmoAuh/1

解释

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+ 
      ( \S+ )                       # (1), from <module>
      [ ]+ 
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>
 [ ]* 
 $                             # End of line

或者,如果您想匹配 as 但不想捕获任何内容,请使用它。

(?m)^(?:from[ ]+(\S+)[ ]+)?import[ ]+(\S+)(?:[ ]+as[ ]+\S+)?[ ]*$

https://regex101.com/r/xFtey5/1

展开

 (?m)                          # Modifiers: multi-line
 ^                             # Beginning of line
 (?:                           # Optional from
      from [ ]+ 
      ( \S+ )                       # (1), from <module>
      [ ]+ 
 )?

 import [ ]+                   # Required import
 ( \S+ )                       # (2), import <module>

 (?:                           # Optional as
      [ ]+ 
      as [ ]+ 
      \S+                          # <alias>
 )?
 [ ]* 
 $ 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多