我试图在python中学习令牌。基本上我所知道的是令牌是python识别python程序的不同对象的一种方式。
我试着这样玩:
from tokenize import generate_tokens
generate_tokens('hello this is a test string')
我收到了一个错误:
<generator object generate_tokens at 0x028D7238>
我期待显示一系列元组。
有人可以向我解释令牌的概念以及如何在python中生成它们吗?哪些python模块包含使用令牌的方法?
答案 0 :(得分:3)
你犯了两个错误:
list()
包装它以便以交互方式显示结果(编程访问需要生成器表单)。file().readline
修复了ipython
中的代码和输出,以便更好地打印列表:
In [1]: from tokenize import generate_tokens
In [2]: from cStringIO import StringIO
In [3]: list(generate_tokens(StringIO('hello this is a test string').readline))
Out[3]:
[(1, 'hello', (1, 0), (1, 5), 'hello this is a test string'),
(1, 'this', (1, 6), (1, 10), 'hello this is a test string'),
(1, 'is', (1, 11), (1, 13), 'hello this is a test string'),
(1, 'a', (1, 14), (1, 15), 'hello this is a test string'),
(1, 'test', (1, 16), (1, 20), 'hello this is a test string'),
(1, 'string', (1, 21), (1, 27), 'hello this is a test string'),
(0, '', (2, 0), (2, 0), '')]
对于下一级(解析),请使用标准ast
模块或第三方logilab.astng
包。