2014-10-10 63 views
0

我想了解Python中的令牌。基本上我所知道的是令牌是python识别python程序的不同对象的一种方式。Python如何使用令牌

我试图玩弄像这样:

from tokenize import generate_tokens 
generate_tokens('hello this is a test string') 

我得到了一个错误:

<generator object generate_tokens at 0x028D7238> 

我预计将显示一系列的元组。

有人可以向我解释令牌的概念以及如何在python中生成它们吗?哪些python模块包含使用令牌的方法?

回答

3

你让两个错误:

  • generate_tokens返回一个迭代,而不是一个列表,所以你需要以交互方式显示结果(编程访问的希望发生器的形式)与list()把它包起来。
  • 参数不是一个字符串,而是返回字符串的调用,以在ipythonfile().readline

固定码和输出的方式,因此很版画列出更好:

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包。