繁体   English   中英

Python如何使用令牌

[英]Python how to work with tokens

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

我试着这样玩:

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

我收到一个错误:

<generator object generate_tokens at 0x028D7238>

我期望显示一系列元组。

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

您犯了两个错误:

  • generate_tokens返回一个可迭代的列表,而不是列表,因此您需要使用list()包装它,以便以交互方式显示结果(编程访问需要生成器形式)。
  • 参数不是字符串,而是以file().readline的方式返回字符串的callable 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软件包。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM