Python检测字符串字节编码 [英] Python detect string byte encoding
本文介绍了Python检测字符串字节编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有大约1000个文件名被os.listdir()
读取,其中一些被编码为'utf-8',有些是'cp1252'。
我想将所有这些都解码为unicode,以便在我的脚本中进一步处理。有没有办法让源代码正确解码成unicode? p>
示例:
os.listdir(rootPath)中的项目:
#转换为Unicode
如果isinstance(item,str):
item = item.decode 'cp1252')#或item = item.decode('utf-8')
打印项
解决方案
如果您的文件在 cp1252
和 utf-8
那么有一个简单的方法。
import logging
def force_decode(string,codecs = ['utf8',' cp1252']):
对于我在编解码器:
尝试:
返回string.decode(i)
除了UnicodeDecodeError:
通过
logging.warn(can not decode url%s%([string]))
for os.listdir(rootPath)中的项目:
#转换为Unicode
if isinstance(item,str):
item = force_decode(item)
打印项
否则,有一个字符集检测库。
https://pypi.python.org/pypi/chardet
I've got about 1000 filenames read by os.listdir() some of them are encoded 'utf-8' 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
这篇关于Python检测字符串字节编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文