python chardet无法正确检测utf-8

时间:2017-09-09 14:36:09

标签: python encode chardet

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import chardet
s = '123'.encode('utf-8')
print(s)
print(chardet.detect(s))

ss ='编程'.encode('utf-8')
print(chardet.detect(ss))

和结果

b'123'
{'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
{'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''}

为什么它无法将s检测为UTF-8?

为什么是ASCII?

这条线路没用吗? # -*- coding: utf-8 -*- Python新手,谢谢!

1 个答案:

答案 0 :(得分:0)

让我们谈谈这些问题 - 所有的肉都在那里:

s = '123'.encode('utf-8')
print(s)

默认情况下,Python 3使用Unicode是正确的。当您说'123'.encode()时,您正在将Unicode字符串转换为字节序列,然后使用丑陋的b前缀进行打印,以提醒您它不是默认类型的字符串。