Python如何使用令牌

时间:2014-10-10 04:01:35

标签: python token tokenize

我试图在python中学习令牌。基本上我所知道的是令牌是python识别python程序的不同对象的一种方式。

我试着这样玩:

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

我收到了一个错误:

<generator object generate_tokens at 0x028D7238>

我期待显示一系列元组。

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

1 个答案:

答案 0 :(得分:3)

你犯了两个错误:

  • generate_tokens返回一个可迭代的,而不是一个列表,所以你需要用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包。