V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

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

  •  
  •   vtoexsir · 2017-09-09 10:35:27 +08:00 · 2864 次点击
    这是一个创建于 2413 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    7 条回复    2017-09-10 23:08:30 +08:00
    nullcc
        1
    nullcc  
       2017-09-09 10:42:08 +08:00
    mskip
        2
    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
        3
    vtoexsir  
    OP
       2017-09-09 10:57:21 +08:00
    @nullcc
    @mskip
    chardet 不能指定检查哪种编码的概率。比如指定一段文本检查 gbk 编码的概率是多少。
    ltux
        4
    ltux  
       2017-09-09 13:18:10 +08:00
    那就自己实现喽。
    janxin
        5
    janxin  
       2017-09-09 14:02:43 +08:00   ❤️ 1
    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
        6
    param  
       2017-09-09 19:11:35 +08:00
    chardet 有出错的,而且速度很慢
    yucongo
        7
    yucongo  
       2017-09-10 23:08:30 +08:00
    s = '**************', 貌似少个 b 吧,s = b'**************'。str 是不存在编码的问题的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3284 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 12:25 · PVG 20:25 · LAX 05:25 · JFK 08:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.