python中文乱码 def decode-python处理一些乱码的中文文本时decode('utf-8')报错的处理...

用python写脚本时,遇到处理中文(乱码的中文)时,用decode("utf-8")会发现始终会报错

>>> txt_from = open("/home/love/ex130705.log")

>>> txt_from_iter= iter(txt_from)

>>> txt_proc = txt_from_iter.next().decode("utf-8", "ignore")

Traceback (most recent call last):

File "/tmp/py4049kjX", line 41, in

txt_proc = txt_from_iter.next().decode("utf-8")

File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode

return codecs.utf_8_decode(input, errors, True)

UnicodeDecodeError: "utf8" codec can"t decode bytes in position 84-85: invalid continuation byte

欲处理的原文件中部分显示为乱码:

2013-07-05 04:20:10 192.168.1.5 GET /Portals/0/鏁欒偛淇℃伅鏂囦欢澶 校园 80 - 25.XXX.10.99 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+Alexa+Toolbar) 404 0 2 234

2013-07-05 04:20:24 192.168.1.5 GET /Portals/0/鏁欒偛淇℃伅鏂囦欢澶 校园 80 - 25.XXX.10.99 Mozilla/4.0+(compatible;+MSIE+8.0;+Windows+NT+5.1;+Trident/4.0;+Alexa+Toolbar) 404 0 2 296

这些显示乱码的中文字符是IIS在记录日志过程中出现的。python通过decode("utf-8")解码为UTF-8时会抛出异常UnicodeDecodeError。

解决:用 decode("utf-8", "ignore")

>>>

>>> txt_proc = txt_from_iter.next().decode("utf-8", "ignore")

>>>

查看decode的帮助:

help("".decode)

decode(...)

S.decode([encoding[,errors]]) -> object

Decodes S using the codec registered for encoding. encoding defaults

to the default encoding. errors may be given to set a different error

handling scheme. Default is "strict" meaning that encoding errors raise

a UnicodeDecodeError. Other possible values are "ignore" and "replace"

as well as any other name registered with codecs.register_error that is

able to handle UnicodeDecodeErrors.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,处理中文乱码通常涉及到编码和解码的问题。如果你遇到中文字符串乱码,可以遵循以下几个步骤: 1. **导入必要的模块**:确保你使用了`codecs`模块,它是Python处理文本编码和解码的标准库。 ```python import codecs ``` 2. **设置正确的编码**:当你读取或写入文件,指定正确的字符编码。比如,如果你的文件是UTF-8编码,可以这样处理: ```python # 读取文件 with codecs.open('文件名', 'r', 'utf-8') as f: content = f.read() # 写入文件 with codecs.open('新文件名', 'w', 'utf-8') as f: f.write(content) ``` 3. **字符串操作**:如果你处理的是字符串,确保在字符串操作也使用相同的编码,避免编码不匹配导致乱码。例如: ```python str_with_chinese = "你好,世界" # 转换成UTF-8编码 utf8_str = str_with_chinese.encode('utf-8') # 或者从UTF-8解码为原始字符串 decoded_str = utf8_str.decode('utf-8') ``` 4. **异常处理**:如果不确定文件的编码,可以尝试检测并自动转换: ```python def smart_open(filename, mode): encoding = detect_encoding(filename) # 自定义函数检测编码 return codecs.open(filename, mode, encoding) def detect_encoding(filename): # 使用chardet库或其他方法检测文件编码 with open(filename, 'rb') as f: result = chardet.detect(f.read()) return result['encoding'] ``` 相关问题: 1. Python中常用的中文字符编码有哪些? 2. 如何在处理网络请求避免中文乱码? 3. 在Python 3中,字符串默认的编码是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值