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 相关文章推荐
win10系统中安装scrapy-1.1
Jul 03 Python
pandas带有重复索引操作方法
Jun 08 Python
Flask框架工厂函数用法实例分析
May 25 Python
python绘制评估优化算法性能的测试函数
Jun 25 Python
python 计算平均平方误差(MSE)的实例
Jun 29 Python
django-allauth入门学习和使用详解
Jul 03 Python
Python如何实现强制数据类型转换
Nov 22 Python
django2.2 和 PyMySQL版本兼容问题
Feb 17 Python
Python pathlib模块使用方法及实例解析
Oct 05 Python
python 实现ping测试延迟的两种方法
Dec 10 Python
浅谈盘点5种基于Python生成的个性化语音方法
Feb 05 Python
Python基本数据类型之字符串str
Jul 21 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中for循环语句的几种变型
2007/03/16 PHP
PHP 日常开发小技巧
2009/09/23 PHP
phpstorm编辑器乱码问题解决
2014/12/01 PHP
PHP使用Face++接口开发微信公众平台人脸识别系统的方法
2015/04/17 PHP
tp5.1 框架查询表达式用法详解
2020/05/25 PHP
JavaScript.The.Good.Parts阅读笔记(一)假值与===运算符
2010/11/16 Javascript
能说明你的Javascript技术很烂的五个原因分析
2011/10/28 Javascript
JS字符串累加Array不一定比字符串累加快(根据电脑配置)
2012/05/14 Javascript
微信js-sdk地理位置接口用法示例
2016/10/12 Javascript
微信小程序 向左滑动删除功能的实现
2017/03/10 Javascript
详解微信小程序开发(项目从零开始)
2019/06/06 Javascript
用JS实现选项卡
2020/03/23 Javascript
node.js通过Sequelize 连接MySQL的方法
2020/12/28 Javascript
[53:15]Mineski vs iG 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
详解Python中内置的NotImplemented类型的用法
2015/03/31 Python
通过代码实例展示Python中列表生成式的用法
2015/03/31 Python
python迭代器与生成器详解
2016/03/10 Python
Python基于回溯法子集树模板解决数字组合问题实例
2017/09/02 Python
python使用Tkinter实现在线音乐播放器
2018/01/30 Python
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
2018/07/17 Python
Django 限制用户访问频率的中间件的实现
2018/08/23 Python
Python3实现统计单词表中每个字母出现频率的方法示例
2019/01/28 Python
用python打印1~20的整数实例讲解
2019/07/01 Python
python中bs4.BeautifulSoup的基本用法
2019/07/27 Python
Python对象的属性访问过程详解
2020/03/05 Python
NHL官方在线商店:Shop.NHL.com
2020/05/01 全球购物
总经理办公室主任岗位职责
2013/11/12 职场文书
餐饮主管岗位职责
2013/12/10 职场文书
端午节粽子促销活动方案
2014/02/02 职场文书
中学生获奖感言
2014/02/04 职场文书
创先争优活动方案
2014/02/12 职场文书
新闻编辑求职信
2014/07/13 职场文书
五好家庭申报材料
2014/12/20 职场文书
公司业务员管理制度
2015/08/05 职场文书
2019年销售部季度工作计划3篇
2019/10/09 职场文书
Python常用配置文件ini、json、yaml读写总结
2021/07/09 Python