【问题标题】:chardet run incorrect in python 3chardet 在 python 3 中运行不正确
【发布时间】:2012-09-10 14:22:42
【问题描述】:


我在python 3.2中使用chardet 2.01,源代码如本站http://getpython3.com/diveintopython3/case-study-porting-chardet-to-python-3.html

可以在这里下载
http://jaist.dl.sourceforge.net/project/cygwin-ports/release-2/Python/python3-chardet/python3-chardet-2.0.1-2.tar.bz2

我使用 lxml2 解析 html 以获取一些字符串
,并使用下面的代码来检测编码

chardet.detect(name)

但是发生了错误

Traceback (most recent call last):
  File "C:\python\test.py", line 125, in <module>
    print(chardet.detect(str(name)))
  File "E:\Python32\lib\site-packages\chardet\__init__.py", line 24, in detect
    u.feed(aBuf)
  File "E:\Python32\lib\site-packages\chardet\universaldetector.py", line 98, in feed
    if self._highBitDetector.search(aBuf):
TypeError: can't use a bytes pattern on a string-like object

name 是一个字符串对象
将字符串转换为字节意味着使用 'utf-8'、'big5'
等编码对其进行编码,charset 会检测您所做的编码......而不是原始字符串的编码
我不知道这个问题...

【问题讨论】:

  • 你为什么在不知道编码的情况下打电话给str()
  • 您的name 对象中有什么?它不应该是 b'something' 而应该只是 'something' - 一个字符串。
  • 是的,'name' 是一个字符串对象。但是,如果我将其转换为字节,我必须对其进行编码......导致 chardet.detect 变得无用
  • @eternalblaze:Python 3 str 没有编码;它是一个 unicode 字符序列。只讨论bytes 对象使用的编码是有意义的。
  • 我只是想让大家明白我要检测字符串对象...

标签: python encoding python-3.x chardet


【解决方案1】:

问题很明显,您是在字符串而不是字节对象上调用chardet。您缺少的是对于 Python,字符串 已经解码。它没有编码了。

您必须修复您的代码,以便在将原始字节解码为字符串之前将其提供给chardet。如果您从另一个包中获取字符串,那么它已经确定了编码,您无能为力。

【讨论】:

  • 但是为什么 chardet 在 python 2.x 中可以正常运行呢?
    stackoverflow.com/questions/2686709/…>
  • @eternalblaze:您链接到的示例不会尝试检测已解码字符串的编码,而是检测原始字节串的编码(有点令人困惑,它是str in蟒蛇2)。
  • @eternalblaze,Python 2 不区分字符串和未编码的字节串。 Python 3 更加严格,现在需要您知道其中的区别。您需要跟踪您拥有哪种类型以及谁在进行转化。
猜你喜欢
  • 2021-08-22
  • 2017-12-03
  • 2011-03-26
  • 2018-01-20
  • 2019-10-28
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 2012-01-10
相关资源
最近更新 更多