pyparsing:获取解析数据的结果
我正在尝试使用 pyparsing
来解析一些 SQL
语句,具体来说是 CREATE TABLE
语句。为了处理数据库名称和表名称,我创建了标识符:
identifier = (Combine(Optional('"') + Word(alphanums) +
ZeroOrMore('_' + Word(alphanums)) +
Optional('"')) & ~keywords_set)
database_name = identifier.setResultsName('database_name')
table_name = identifier.setResultsName('table_name')
我还在使用这种解析方法:
def parse(self, sql):
try:
tokens = self.create_table_stmt.parseString(sql)
print tokens.database_name, tokens.table_name
values = tokens.database_name, tokens.table_name
print values
return values
except ParseException as error:
print error
对于以下输入:
CreateTableParser().parse('''
CREATE TABLE "django"."django_site1" (
)''')
我得到的是:
['"django"'] ['"django_site1"']
((['"django"'], {}), (['"django_site1"'], {}))
为什么这些结果会不同?我怎么才能像第一种那样,得到简单的列表输出?我只有在打印这些值的时候才能得到。
1 个回答
1
在 print a, b
和 print (a,b)
之间是有区别的:
>>> a, b = "ab"
>>> a
'a'
>>> b
'b'
>>> print a, b
a b
>>> print (a, b)
('a', 'b')
print a, b
会分别打印出两个对象 a
和 b
。而 print (a, b)
则会把这两个对象当作一个整体来打印,形成一个叫做元组的东西 a, b
:
>>> w = sys.stdout.write
>>> _ = w(str(a)), w(' '), w(str(b)), w('\n')
a b
>>> _ = w(str((a,b))), w('\n')
('a', 'b')
换句话说:
>>> class A:
... def __str__(self):
... return '1'
... def __repr__(self):
... return 'A()'
...
>>> print A(), A()
1 1
>>> print (A(), A())
(A(), A())
当你使用 str(obj)
时,会调用 __str__
方法。如果没有 __str__
方法,那么就会调用 __repr__
方法,使用 repr(obj)
。