2010-06-18 74 views
1

我想编写修改的Python程序这样的程序:我可以为此使用python ast模块吗?

变化

“的一些文字字符串%” %SOMETHING

functioncall(“一些文字字符串%“)%SOMETHING

谢谢,

+0

使用专为源到源转换设计的2to3工具,您可能会有更好的运气。 – 2010-06-18 13:52:58

回答

1

你可以不必写一个解决这个问题节目。相反,只需使用有史以来最好的编辑器:Emacs。值得学习,如果你还没有。有了它,你可以使用它的正则表达式替换功能来解决这个问题。唯一的麻烦是我很少使用正则表达式,因此我总是忘记了隐含语法的细节,并且仍然需要查看它:P我会尝试再次为您找到它。下面是对Search & Replace Info for Emacs - scroll down for using regex's

+1

我需要一种方法来完成它,所以我可以将它作为一种预处理程序包含在另一个程序中。 – 2010-06-18 13:03:24

+0

[Melodrama](http://en.wikipedia.org/wiki/Melodrama)tically,是吧?但是如果你想以代码方式进行,那么只需使用python的're'模块来处理正则表达式。 – JAB 2010-06-18 14:42:43

+0

Melodramatically我键入?拼写检查器。我是编程式的。 – 2010-06-18 15:24:55

2

的链接可能是与tokenize简单 - 适应在文档的例子,

import cStringIO 
import tokenize 

class Lookahead(object): 

    def __init__(self, s): 
    self._t = tokenize.generate_tokens(cStringIO.StringIO(s).readline) 
    self.lookahead = next(self._t, None) 

    def __iter__(self): 
    return self 

    def next(self): 
    result = self.lookahead 
    if result is None: raise StopIteration 
    self.lookahead = next(self._t, None) 
    return result 


def doit(s): 
    toks = Lookahead(s) 
    result = [] 
    for toktype, tokvalue, _, _, _ in toks: 
    if toktype == tokenize.STRING: 
     pk = toks.lookahead 
     if pk is not None and pk[0] == tokenize.OP and pk[1] == '%': 
     result.extend([ 
      (tokenize.NAME, 'functioncall'), 
      (tokenize.OP, '('), 
      (tokenize.STRING, repr(tokvalue)), 
      (tokenize.OP, ')') 
     ]) 
     continue 
    result.append((toktype, tokvalue)) 
    return tokenize.untokenize(result) 


print doit('"some literal string %" % SOMETHING') 

这将打印functioncall ('"some literal string %"')%SOMETHING。间距非常奇特(需要花费更多精力才能使间距恰到好处 - 但对于从修改后的AST重新构建资源来说更是如此),但是如果您要做的只是导入/运行导致的代码(如果你想要得到很好的可读性和可编辑的代码,就不那么好了 - 但这是一个足够大的问题,我建议单独的Q ;-)。

+0

与OP所要求的相比,似乎存在不需要的引号。我相信用tokvalue代替repr(tokvalue)可以得到理想的结果。 – 2015-10-13 19:40:39

0

Here是另一个可能有用的SO问题。

我收集了ast模块没有一个工厂返回到源代码,但阿明Ronacher写了一个模块codegen它实现了这一点做的ast节点to_source功能。

我还没有试图自己做这个。

+0

该codegen模块不适用于每个Python代码:( – 2010-06-18 15:23:10

0
import re 

pattern = r'(".+? %")(?= %)' 
oldstr = '"some literal string %" % SOMETHING' 

newstr = re.sub(pattern, r'functioncall(\1)', oldstr) 

尝试类似的东西。 (当然,尽管有文件I/O)。我还没有和ast一起工作过,所以我真的不知道如果使用它会比这更容易,但在我看来,如果你我只是在做一个简单的搜索替换,而实际上并没有做很多复杂的分析,因此不需要使用ast

相关问题