【问题标题】:Python3.0: tokenize & BytesIOPython3.0:标记化 & BytesIO
【发布时间】:2009-05-27 00:22:37
【问题描述】:

在 python3.0 中尝试tokenize 字符串时,为什么我会在标记开始之前得到前导'utf-8'

python3 docs 开始,tokenize 现在应该按如下方式使用:

g = tokenize(BytesIO(s.encode('utf-8')).readline)

但是,当在终端尝试此操作时,会发生以下情况:

>>> from tokenize import tokenize
>>> from io import BytesIO
>>> g = tokenize(BytesIO('foo'.encode()).readline)
>>> next(g)
(57, 'utf-8', (0, 0), (0, 0), '')
>>> next(g)
(1, 'foo', (1, 0), (1, 3), 'foo')
>>> next(g)
(0, '', (2, 0), (2, 0), '')
>>> next(g)

utf-8 标记在其他标记之前是怎么回事?这应该发生吗?如果是这样,那么我应该总是跳过第一个令牌吗?

[编辑]

我发现令牌类型 57 是 tokenize.ENCODING,如果需要,可以轻松地将其从令牌流中过滤掉。

【问题讨论】:

    标签: python io tokenize bytesio


    【解决方案1】:

    那是源代码的 cookie。您可以明确指定一个:

    # -*- coding: utf-8 -*-
    do_it()
    

    否则,Python 会采用默认编码,即 Python 3 中的 utf-8。

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2010-10-31
      • 2010-10-23
      • 2014-01-02
      • 1970-01-01
      • 2016-10-30
      • 2010-12-05
      • 2021-04-06
      • 2010-11-19
      相关资源
      最近更新 更多