Python3.0: 标记化与BytesIO

1 投票
1 回答
690 浏览
提问于 2025-04-15 11:51

在尝试用 python3.0 对一个字符串进行 tokenize(分词)时,为什么我会在分词开始前看到一个 'utf-8' 的标记呢?

根据 python3 的文档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,如果需要的话,可以很容易地从标记流中过滤掉。

1 个回答

2

这段代码是关于源代码的编码设置。你可以明确地指定一种编码方式:

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

否则,Python会默认使用utf-8编码,这在Python 3中是这样的。

撰写回答