1

我正在尝试替换 Python 源文件中的每个多行导入。所以,源代码就像

from XXX import (
   AAA,
   BBB,
)
from YYY import (
   CCC,
   DDD,
   EEE,
   ...
)
...other instructions...

我想得到类似的东西

from XXX import AAA, BBB
from YYY import CCC, DDD, EEE, ...
...other instructions...

我尝试使用 sed,但它看起来不支持右括号的非贪婪匹配,所以它“吃掉”第二个导入.. :(
任何提示?这对 sed 来说是不可能的吗?我应该尝试使用其他工具吗?

4

3 回答 3

2

这可能对您有用:

sed '/^from/,/^)/{H;//{x;/)/{s/[\n()]//g;s/  */ /g;s/,$//;p;x}};d}' source
from XXX import AAA, BBB
from YYY import CCC, DDD, EEE, ...
...other instructions...
于 2011-12-22T16:40:26.160 回答
1

嗯...... Python有什么问题?

lineIter= iter(aFile)
for aLine in lineIter:
    if aLine.startswith("import"):
        if aLine.endswith("("):
            for aModule in lineIter:
                if aModule.endwith(")"):
                    break
                print "import", aModule.strip()
        else:
            print aLine.stri()
    else:
        print aLine.strip()
于 2008-12-15T11:04:52.513 回答
1

对于后人,这里是 S.Lott 脚本的一个稍微完善的版本(我会将其作为评论发布,但它太长了 ^^; ).. 这个版本保留了缩进并产生了更接近我的示例的结果。

lineIter=iter(aFile)
对于 lineIter 中的 aLine:
    s = aLine.strip()
    如果 s.startswith("from ") 和 s.endswith("("):
        完成 = s[:-1]
        对于 lineIter 中的模块:
            m = aModule.strip()
            如果 m.endswith(")"):
                休息
            完成 += m.strip()
        打印完成
    别的:
        打印一行,
于 2008-12-15T13:06:01.333 回答