unwind在2.6中使用ast模塊的建議是一個不錯的選擇。 (這裏還有2.5中沒有記錄的_ast模塊。)下面是示例代碼
code = """a = 'blah'
b = '''multi
line
string'''
c = u"spam"
"""
import ast
root = ast.parse(code)
class ShowStrings(ast.NodeVisitor):
def visit_Str(self, node):
print "string at", node.lineno, node.col_offset, repr(node.s)
show_strings = ShowStrings()
show_strings.visit(root)
問題是多行字符串。如果你運行上述,你會得到。
string at 1 4 'blah'
string at 4 -1 'multi\nline\nstring'
string at 5 4 u'spam'
您會發現它不報告多行字符串的開始,只是結束。使用內置的Python工具沒有好的解決方案。
另一種選擇是你可以使用我的'python4ply'模塊。這是一個用於PLY的Python的語法定義,它是一個解析器生成器。下面是如何使用它:
import compiler
import compiler.visitor
# from python4ply; requires the ply parser generator
import python_yacc
code = """a = 'blah'
b = '''multi
line
string'''
c = u"spam"
d = 1
"""
tree = python_yacc.parse(code, "<string>")
#print tree
class ShowStrings(compiler.visitor.ASTVisitor):
def visitConst(self, node):
if isinstance(node.value, basestring):
print "string at", node.lineno, repr(node.value)
visitor = ShowStrings()
compiler.walk(tree, visitor)
從這個輸出是
string at 1 'blah'
string at 2 'multi\nline\nstring'
string at 5 u'spam'
有列信息的支持。 (有一些主要完整的註釋代碼來支持這一點,但它沒有經過充分測試。)然後再次,我看到你不需要它。這也意味着使用Python的「編譯器」模塊,它比AST模塊笨拙。
儘管如此,使用30-40行代碼,您應該完全按照您的要求。
,如果你打算對信息採取行動:「文件名,行號,字符串」然後STDLIB的lib2to3庫可能給你如何重構大規模Python代碼的一些想法,尤其是lib2to3/refactor.py文件。你可能只需要爲它編寫自己的夾具,就完成了。 – jfs 2009-02-25 14:25:01