如何检测字符串字节编码? [英] How to detect string byte encoding?

查看:94
本文介绍了如何检测字符串字节编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过 os.listdir()读取了大约1000个文件名,其中一些使用UTF8编码,而某些则使用CP1252。



我想将它们全部解码为Unicode,以便在脚本中进行进一步处理。有没有办法使源编码正确解码为Unicode?

示例:

 用于os.listdir(rootPath)中的项目:

#如果isinstance(item,str)转换为Unicode

item = item.decode( 'cp1252')#或item = item.decode('utf-8')
打印项目


解决方案

如果您的文件位于 cp1252 utf-8 中,

  import logging 
def force_decode(string,codecs = ['utf8',' cp1252']):
用于编解码器中的i:
尝试:
返回string.decode(i)
,UnicodeDecodeError除外:
传递

logging.warn(无法解码url%s%([字符串]))

表示os.listdir(rootPath)中的项目:
#转换为Unicode
isinstance(item,str):
项目= force_decode(item)
打印项目



< >



Python-检测字符集并转换为utf-8



https://pypi.python.org/pypi/chardet


I've got about 1000 filenames read by os.listdir(), some of them are encoded in UTF8 and some are CP1252.

I want to decode all of them to Unicode for further processing in my script. Is there a way to get the source encoding to correctly decode into Unicode?

Example:

for item in os.listdir(rootPath):

    #Convert to Unicode
    if isinstance(item, str):
        item = item.decode('cp1252')  # or item = item.decode('utf-8')
    print item

解决方案

if your files either in cp1252 and utf-8, then there is an easy way.

import logging
def force_decode(string, codecs=['utf8', 'cp1252']):
    for i in codecs:
        try:
            return string.decode(i)
        except UnicodeDecodeError:
            pass

    logging.warn("cannot decode url %s" % ([string]))

for item in os.listdir(rootPath):
    #Convert to Unicode
    if isinstance(item, str):
        item = force_decode(item)
    print item

otherwise, there is a charset detect lib.

Python - detect charset and convert to utf-8

https://pypi.python.org/pypi/chardet

这篇关于如何检测字符串字节编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆