Python 转换文本编码实现解析


Posted in Python onAugust 27, 2019

最近在做周报的时候,需要把csv文本中的数据提取出来制作表格后生产图表。

在获取csv文本内容的时候,基本上都是用with open(filename, encoding ='UTF-8') as f:来打开csv文本,但是实际使用过程中发现有些csv文本并不是utf-8格式,从而导致程序在run的过程中报错,每次都需要手动去把该文本文件的编码格式修改成utf-8,再次来run该程序,所以想说:直接在程序中判断并修改文本编码。

基本思路:先查找该文本是否是utf-8的编码,如果不是则修改为utf-8编码的文本,然后再处理。

python有chardet库可以查看到文本的encoding信息:

detect函数只需要一个 非unicode字符串参数,返回一个字典(例如:{'encoding': 'utf-8', 'confidence': 0.99})。该字典包括判断到的编码格式及判断的置信度。

import chardet
def get_encode_info(file):
  with open(file, 'rb') as f:
    return chardet.detect(f.read())['encoding']

不过这个在从处理小文件的时候性能还行,如果文本稍微过大就很慢了,目前我本地的csv文件是近200k,就能明显感觉到速度过慢了,效率低下。不过chardet库中提供UniversalDetector对象来处理:创建UniversalDetector对象,然后对每个文本块重复调用其feed方法。如果检测器达到了最小置信阈值,它就会将detector.done设置为True。

一旦您用完了源文本,请调用detector.close(),这将完成一些最后的计算,以防检测器之前没有达到其最小置信阈值。结果将是一个字典,其中包含自动检测的字符编码和置信度(与charde.test函数返回的相同)。

from chardet.universaldetector import UniversalDetector
def get_encode_info(file):
 with open(file, 'rb') as f:
    detector = UniversalDetector()
 for line in f.readlines():
      detector.feed(line)
 if detector.done:
 break
    detector.close()
 return detector.result['encoding']

在做编码转换的时候遇到问题:UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 178365: character maps to <undefined>

def read_file(file):
 with open(file, 'rb') as f:
 return f.read()
def write_file(content, file):
 with open(file, 'wb') as f:
    f.write(content)
def convert_encode2utf8(file, original_encode, des_encode):
  file_content = read_file(file)
  file_decode = file_content.decode(original_encode)  #-->此处有问题
  file_encode = file_decode.encode(des_encode)
  write_file(file_encode, file)

这是由于byte字符组没解码好,要加另外一个参数errors。官方文档中写道:

bytearray.decode(encoding=”utf-8”, errors=”strict”)

Return a string decoded from the given bytes. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

意思就是字符数组解码成一个utf-8的字符串,可能被设置成不同的处理方案,默认是‘严格'的,有可能抛出UnicodeError,可以改成‘ignore','replace'就能解决。

所以将此行代码file_decode = file_content.decode(original_encode)修改成file_decode = file_content.decode(original_encode,'ignore')即可。

完整代码:

from chardet.universaldetector import UniversalDetector

def get_encode_info(file):
 with open(file, 'rb') as f:
   detector = UniversalDetector()
   for line in f.readlines():
     detector.feed(line)
     if detector.done:
       break
   detector.close()
   return detector.result['encoding']

def read_file(file):
  with open(file, 'rb') as f:
    return f.read()

def write_file(content, file):
  with open(file, 'wb') as f:
    f.write(content)

def convert_encode2utf8(file, original_encode, des_encode):
  file_content = read_file(file)
  file_decode = file_content.decode(original_encode,'ignore')
  file_encode = file_decode.encode(des_encode)
  write_file(file_encode, file)

if __name__ == "__main__":
  filename = r'C:\Users\danvy\Desktop\Automation\testdata\test.csv'
  file_content = read_file(filename)
  encode_info = get_encode_info(filename)
  if encode_info != 'utf-8':
    convert_encode2utf8(filename, encode_info, 'utf-8')
  encode_info = get_encode_info(filename)
  print(encode_info)

参考:https://chardet.readthedocs.io/en/latest/usage.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现的文件同步服务器实例
Jun 02 Python
Pycharm 设置自定义背景颜色的图文教程
May 23 Python
python 借助numpy保存数据为csv格式的实现方法
Jul 04 Python
对tensorflow 的模型保存和调用实例讲解
Jul 28 Python
在python中安装basemap的教程
Sep 20 Python
Python中staticmethod和classmethod的作用与区别
Oct 11 Python
django 配置阿里云OSS存储media文件的例子
Aug 20 Python
python有序查找算法 二分法实例解析
Feb 18 Python
python 中不同包 类 方法 之间的调用详解
Mar 09 Python
浅谈keras中的Merge层(实现层的相加、相减、相乘实例)
May 23 Python
pytorch中[..., 0]的用法说明
May 20 Python
总结Python使用过程中的bug
Jun 18 Python
python-opencv获取二值图像轮廓及中心点坐标的代码
Aug 27 #Python
python定位xpath 节点位置的方法
Aug 27 #Python
python实现截取屏幕保存文件,删除N天前截图的例子
Aug 27 #Python
python自动化UI工具发送QQ消息的实例
Aug 27 #Python
python 调用pyautogui 实时获取鼠标的位置、移动鼠标的方法
Aug 27 #Python
对Python获取屏幕截图的4种方法详解
Aug 27 #Python
python对常见数据类型的遍历解析
Aug 27 #Python
You might like
php mssql 时间格式问题
2009/01/13 PHP
php使用$_POST或$_SESSION[]向js函数传参
2014/09/16 PHP
PHP中new static() 和 new self() 的区别介绍
2015/01/09 PHP
PHP中JSON的应用技巧
2015/10/10 PHP
PHP编程中尝试程序并发的几种方式总结
2016/03/21 PHP
php打包压缩文件之ZipArchive方法用法分析
2016/04/30 PHP
golang实现php里的serialize()和unserialize()序列和反序列方法详解
2018/10/30 PHP
PHP _construct()函数讲解
2019/02/03 PHP
PHP生成zip压缩包的常用方法示例
2019/08/22 PHP
不错的新闻标题颜色效果
2006/12/10 Javascript
In Javascript Class, how to call the prototype method.(three method)
2007/01/09 Javascript
JavaScript 新手24条实用建议[TUTS+]
2009/06/21 Javascript
jquery实现的随机多彩tag标签随机颜色和字号大小效果
2014/03/27 Javascript
jQuery中[attribute!=value]选择器用法实例
2014/12/31 Javascript
js实现跨域的几种方法汇总(图片ping、JSONP和CORS)
2015/10/25 Javascript
Jquery和BigFileUpload实现大文件上传及进度条显示
2016/06/27 Javascript
Nodejs抓取html页面内容(推荐)
2016/08/11 NodeJs
jQuery实现的自适应焦点图效果完整实例
2016/08/24 Javascript
深入理解JavaScript中的并行处理
2016/09/22 Javascript
简单实现jQuery弹幕效果
2017/05/06 jQuery
vue+axios+element ui 实现全局loading加载示例
2018/09/11 Javascript
Vue中props的详解
2019/05/16 Javascript
Node 使用express-http-proxy 做api网关的实现
2020/10/15 Javascript
[02:28]DOTA2英雄基础教程 灰烬之灵
2013/12/19 DOTA
[01:03:22]LGD vs OG 2018国际邀请赛淘汰赛BO3 第一场 8.25
2018/08/29 DOTA
jupyter notebook 多环境conda kernel配置方式
2020/04/10 Python
Python OpenCV读取中文路径图像的方法
2020/07/02 Python
法国太阳镜店:Sunglasses Shop
2016/08/27 全球购物
生物科学专业职业规划书范文
2014/02/11 职场文书
学生夜不归宿检讨书
2014/09/23 职场文书
初婚未育证明样本
2014/10/24 职场文书
财务会计实训报告
2014/11/05 职场文书
2014年体育教学工作总结
2014/12/09 职场文书
内勤岗位职责范本
2015/04/13 职场文书
《圆的周长》教学反思
2016/02/17 职场文书
基于Nginx实现限制某IP短时间访问次数
2021/03/31 Servers