当前位置: 首页 > 编程日记 > 正文

python文本编码转换_Python: 转换文本编码

最近在做周报的时候,需要把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

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)

相关文章:

ipone 网页版的iphone

本文摘自:http://www.cocoachina.com/bbs/m/list.php?fid6#list

import static

import static(静态导入)是JDK1.5中的新特性,一般我们导入一个类都用 import com.....ClassName;而静态导入是这样:import static com.....ClassName.*;这里多了个static,还有就是类名ClassName后面多了个 .* &#xf…

poj1423

http://acm.pku.edu.cn/JudgeOnline/problem?id1423n!(log10(sqrt(4.0*acos(0.0)*n))n*(log10(n)-log10(exp(1.0)))1);n1 除外 转载于:https://www.cnblogs.com/FCWORLD/archive/2011/03/12/1982355.html

python缩进在程序中长度统一且强制使用_Python习题纠错1

February, 1991 0.9.1 2.Python语言的缩进只要统一即可,不一定是4个空格(尽管这是惯例)。 Python缩进在程序中长度统一且强制使用. 3.IPO:Input Process Output 4.Python合法命名的首字符不能是数字。 5.Python保留字:…

ASP.NET MVC3 在WebGrid中用CheckBox选中行

分三步走 1.保证你的webgrid包含在form中 using (Html.BeginForm("Assign","Home")) { } 2.在webgrid中加一列checkbox grid.Column(header: "Assign?", format: <text><input class"check-box" id"assi…

Delphi中使用IXMLHTTPRequest如何用POST方式提交带参

http://blog.sina.com.cn/s/blog_51a71c010100gbua.html说明&#xff1a;服务器端为JAVA&#xff0c;编码UTF-8&#xff0c;返回数据编码UTF-8&#xff1b;数据交换格式JSON。procedure TloginForm.loginBtnClick(Sender: TObject);var jo: ISuperObject; //JSON接口 req: IX…

Windows图标:有一些你未必知道的东西

有一天&#xff0c;我的程序在任务栏的应用程序中看起来是这样的很奇怪&#xff0c;我的图标明明不是这样的&#xff0c;在资源管理器的文件夹里面&#xff0c;我的图标能够正常显示&#xff0c;在桌面的任务栏里&#xff0c;也能正常的显示&#xff0c;唯独在任务管理器里显示…

几种函数式编程语言

1、函数式编程语言有&#xff1a;lisp,hashshell,erlang等。 2、在函数中的参数&#xff0c;有一一对应的&#xff0c;也有指定模式的&#xff0c;还有使用能数组。如*argp&#xff08;元组&#xff09;&#xff0c;**argp(字典&#xff09;。 3、在pyphon语言中有一些内置的函…

python逐个读取文件并处理_逐个读取多个文件并用python进行处理

我在python中使用Pybrain&#xff08;神经网络库&#xff09;进行图像处理。我在一个目录中有196个文件&#xff0c;它保存在下面代码中的所有_文件中。我试着打开每个文件并分别对每个文件进行处理&#xff0c;但它将所有文件数据放在一个字符串中&#xff0c;我希望每个文件逐…

HDU 2102 A计划

该题是一道典型的搜索题&#xff0c; #include<stdio.h> #include<stdlib.h> #include<string.h> struct Node {int x, y;int time;int flag; }q[100024]; int d[4][2]{ 0,1,1,0,0,-1,-1,0 }; int N,M; char map[2][13][13]; void getxy( int &X,int &a…

node.js是做什么的?

作者&#xff1a;厂长链接&#xff1a;https://www.zhihu.com/question/33578075/answer/56951771来源&#xff1a;知乎著作权归作者所有。商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处。国外有一篇非常好的Node.js 介绍文章&#xff0c;从原理入手讲解&#x…

K8S - Kubernetes简介

Kubernetes Kubernetes&#xff08;简称K8s&#xff0c;用8代替8个字符“ubernete”&#xff09;是Google开源的一个容器编排引擎&#xff0c;支持自动化部署、大规模可伸缩、应用容器化管理。 Kubernetes 是目前最为广泛且流行的容器编排调度系统&#xff0c;也是现在用来构建…

python中filenotfounderror_Python3 报错 FileNotFoundError: [WinError 2]

Python3 报错 FileNotFoundError: [WinError 2]工具/原料 Python3.7 chromedriver 方法/步骤 1 首先&#xff0c;打开py文件&#xff0c;如图&#xff0c;有如下代码。 import time from selenium import webdriver driver webdriver.Chrome()2 然后运行py文件&#xff0c;run…

Push Notifications

push notification 使用&#xff1a; 参考资源: http://tiny4cocoa.com/thread-1406-1-1.html http://bbs.ldci.com.cn/read.php?tid-19971.html http://www.cocoachina.com/bbs/read.php?tid-3770-keyword-apns.html http://code.google.com/p/apns-python-wrapper/ http://…

[原创]Bash中的$*和$@的区别

2019独角兽企业重金招聘Python工程师标准>>> 在Bash脚本中&#xff0c;$*和$都用于表示执行脚本时所传入的参数。先通过一个例子看看他们的区别: #!/bin/bash # testvar.sh echo "-------------ISF is set to \"-seperator\" ------------" IFS…

文本处理工具之grep和egrep

文本处理工具之grep和egrep grep全称global search regular expression (RE) and print out the line正则表达式&#xff08;一类字符所书写的模式pattern&#xff09; 元字符&#xff1a;不表示字符本身的意义&#xff0c;用于额外功能性的描述基本正则表达式的元字符 字符匹配…

【转】堆栈和托管堆 c#

原文地址&#xff1a;http://blog.csdn.net/baoxuetianxia/archive/2008/11/04/3218913.aspx首先堆栈和堆&#xff08;托管堆&#xff09;都在进程的虚拟内存中。&#xff08;在32位处理器上每个进程的虚拟内存为4GB&#xff09; 堆栈stack 堆栈中存储值类型。 堆栈实际上是向…

python特性和属性_Python之属性、特性和修饰符

原博文 2018-03-17 11:08 − 作为面对对象的核心内容&#xff0c;将从以下一个方面进行总结&#xff1a; 1. property和property 2. __getattribute__()、__getattr__()、__setattr__()、__delattr__() 3. 描述符__get__()、__set__()、__delete__()... 相关推荐 2019-09-28 21…

pytest+allure环境别人电脑运行正常,自己运行不正常几种情况

1. AttributeError&#xff1a;module’ object has no attribute severity_level 之前运行都是正常的&#xff0c;想弄allure报告&#xff0c;就使用pip install allure-pytest 命令安装了&#xff0c;其实该命令的作用是会把你当前版本的pytest卸载掉&#xff0c;然后安装 al…

进驻宝岛 不闪式3D热潮来临?

本来说一直要换眼镜的&#xff0c;现在趁年底有空&#xff0c;专门去逛眼镜店。在逛宝岛的时候&#xff0c;发现了专门设立的不闪式3D体验区&#xff0c;供消费者体验。笔者在宝岛眼镜体验了下3D眼镜&#xff0c;觉得非常不错&#xff0c;特别分享下。自从LG Display开始全面进…

BZOJ3782 上学路线 【dp + Lucas + CRT】

题目链接 BZOJ3782 题解 我们把终点也加入障碍点中&#xff0c;将点排序&#xff0c;令\(f[i]\)表示从\((0,0)\)出发&#xff0c;不经过其它障碍&#xff0c;直接到达\((x_i,y_i)\)的方案数 首先我们有个大致的方案数\({x_i y_i \choose x_i}\) 但是中途可能会经过一些其它障碍…

007本周总结报告

这周感觉自己什么也没做&#xff0c;好没有成就感。这周大部分的时间都用来学车了&#xff0c;自己也是东跑西跑的&#xff0c;然而车也没有学好&#xff0c;java也学习的少的可伶。自己总是感觉自己学车都要忙死了。哪有什么时间学习java啊&#xff0c;能学好车就不错了。其实…

python max函数_Python3

max(x, y[, z...]):Number|Sequence 入参类型不能混入&#xff08;要么全Number(int|float|complex|bool&#xff09;&#xff0c;要么全序列&#xff09;。 入参是序列的话&#xff1a; 单序列入参&#xff0c;返回序列中最大的一个数值多序列入参, 按索引顺序&#xff0c;逐一…

Linux Mount Windows域用户限制的共享文件夹

sud现在一直使用linux作为主要的办公os&#xff0c;但是最近公司统一使用windows域服务器了&#xff0c;共享就出现比较打的问题了&#xff0c;原因如下&#xff1a;1、linux下通常mount windows共享文件夹Linux下使用smbfs形式访问windows共享文件夹是众所周知的事情&#xff…

B-tree索引与Bitmap索引的对比测试

昨天发现一条语句没有走索引&#xff0c;检查发现表没有建相应索引&#xff0c;先建立B-tree索引&#xff0c;测试发现是全表扫描&#xff0c;检查表数据发现此字段的值只有2个,删除原索引又建立bitmap索引&#xff0c;发现还是全表扫描&#xff0c;再次检查数据发现2个值基本各…

python 将字符串转换成字典dict

JSON到字典转化&#xff1a; 输出dict类型 dictinfo json.loads(json_str)字典到JSON转化&#xff1a; 输出str类型 # 比如&#xff1a; info {name : jay, sex : male, age: 22} jsoninfo simplejson.dumps(info) print jsoninfo Unicode到字典的转化&#xff1a; json.loa…

pidstat 命令详解(转载)

转自https://www.jianshu.com/p/3991c0dba094 pidstat 概述 pidstat是sysstat工具的一个命令&#xff0c;用于监控全部或指定进程的cpu、内存、线程、设备IO等系统资源的占用情况。pidstat首次运行时显示自系统启动开始的各项统计信息&#xff0c;之后运行pidstat将显示自上次运…

Oracle中table的大小计算方式

1. Check the size of each table on specific schema ; SQL> select segment_name,bytes/1024/1024 as mb from user_segments; SEGMENT_NAME MB -------------------- ---------- SALES 542. 转载于:https://www.cnblogs.com/jeff…

python编码问题无法复现_Python编码问题详解

1. 基本概念 字符集&#xff08;Character set&#xff09; 解释&#xff1a;文字和符合的总称 常见字符集&#xff1a; Unicode字符集 ASCII字符集&#xff08;Unicode子集&#xff09; GB2312字符集 编码方法&#xff08;Encoding&#xff09; 解释&#xff1a;将字符对应到字…

重新开始 2011/11/25

在csdn上写过几篇文章&#xff0c;始终没有坚持下来&#xff0c;也是由于自己没有一个明确的目标的缘故&#xff1b;当自己感觉乱的时候&#xff0c;总是想改变点东西&#xff0c;重新开始&#xff0c;改变了博客类的东西就真的能重新开始吗&#xff1f;现在我想换个博客就换个…