Python 可否检查某文本为某编码方式的几率?

2017-09-09 10:35:27 +08:00
 vtoexsir

伪代码如下:
s = '**************'
print(detectRisk(s,'gbk') #=>80% s 是 gbk 编码的概率是 80%
print(detectRisk(s,'utf8') #=>30% s 是 u8 编码的概率是 30%
请问 python 有没有这样的方法呢?
有 cchardet.dect(s)或者 chardet.dect(s),但都不能指定检查哪一种编码的概率。

2879 次点击
所在节点    Python
7 条回复
nullcc
2017-09-09 10:42:08 +08:00
mskip
2017-09-09 10:51:26 +08:00
chardet
{'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'}
{'confidence': 1.0, 'language': '', 'encoding': 'ascii'}
{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
{'confidence': 0.99, 'language': '', 'encoding': 'utf-8'}
vtoexsir
2017-09-09 10:57:21 +08:00
@nullcc
@mskip
chardet 不能指定检查哪种编码的概率。比如指定一段文本检查 gbk 编码的概率是多少。
ltux
2017-09-09 13:18:10 +08:00
那就自己实现喽。
janxin
2017-09-09 14:02:43 +08:00
In [1]: import chardet

In [2]: prober = chardet.utf8prober.UTF8Prober()

In [3]: prober.feed('你好,世界!'.encode('utf-8'))
Out[3]: 1

In [4]: prober.get_confidence()
Out[4]: 0.99
param
2017-09-09 19:11:35 +08:00
chardet 有出错的,而且速度很慢
yucongo
2017-09-10 23:08:30 +08:00
s = '**************', 貌似少个 b 吧,s = b'**************'。str 是不存在编码的问题的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/389356

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX