我想在我的大型python项目中列出所有字符串.
想象一下在python中创建字符串的不同可能性:
mystring = "hello world"
mystring = ("hello "
"world")
mystring = "hello " \
"world"
Run Code Online (Sandbox Code Playgroud)
我需要一个工具,为我项目中的每个字符串输出"filename,linenumber,string".使用"\"或"('')"分布在多行上的字符串应显示在一行中.
有什么想法可以做到这一点?
And*_*lke 11
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)
Run Code Online (Sandbox Code Playgroud)
问题是多行字符串.如果你运行上面的,你会得到.
string at 1 4 'blah'
string at 4 -1 'multi\nline\nstring'
string at 5 4 u'spam'
Run Code Online (Sandbox Code Playgroud)
您会看到它不报告多行字符串的开头,只报告结束字符串.使用内置的Python工具没有很好的解决方案.
另一个选择是你可以使用我的' python4ply '模块.这是Python for PLY的语法定义,它是一个解析器生成器.以下是您可以使用它的方法:
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)
Run Code Online (Sandbox Code Playgroud)
这个输出是
string at 1 'blah'
string at 2 'multi\nline\nstring'
string at 5 u'spam'
Run Code Online (Sandbox Code Playgroud)
列信息不支持.(有一些主要是完整的注释代码来支持它,但它没有经过全面测试.)然后,我再次看到你不需要它.它还意味着使用Python的'编译器'模块,它比AST模块更笨拙.
尽管如此,使用30-40行代码,您应该拥有您想要的代码.
小智 7
包含Python的tokenize模块也可以解决这个问题.
from __future__ import with_statement
import sys
import tokenize
for filename in sys.argv[1:]:
with open(filename) as f:
for toktype, tokstr, (lineno, _), _, _ in tokenize.generate_tokens(f.readline):
if toktype == tokenize.STRING:
strrepr = repr(eval(tokstr))
print filename, lineno, strrepr
Run Code Online (Sandbox Code Playgroud)