前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 转换文本编码

Python 转换文本编码

作者头像
py3study
发布2020-01-07 16:34:05
1.2K0
发布2020-01-07 16:34:05
举报
文章被收录于专栏:python3

前段时间入手了一个Sony PRS-505的阅读器,不过因为汉化的原因,折腾了很久,终于全部搞定了。麻烦的是505认得最好的编码方式为utf-8,如果是unicode,当文件大于5M时就容易出现问题。所以许多大的txt文档都要转换成utf-8. 手动转换很麻烦,特别是大的文件,打开就要等一段时间,然后还要转码。所以就想到用刚学的Python去做一个小工具,以后方便处理这些书。

该工具带GUI界面,经测试能够成功的把ANSI格式txt文件转换为utf8。因为主要看feiku的电子书,所以代码中带有自动重命名功能,目前不带批处理能力,以后补上

# -*- coding: cp936 -*- from Tkinter import * import tkFileDialog import tkSimpleDialog import os from os import listdir ipth='' rpth='' def inputpath():         global ipth         InputFile=tkFileDialog.askopenfilename()         print InputFile         ipth=InputFile def chresultdir():         global rpth         OutputDirect=tkSimpleDialog.askstring('Book storage','Input Path',initialvalue="D:/bookresult5")         print OutputDirect         rpth=OutputDirect def processfile():         fopen=open(ipth,"r")         tempcontent=fopen.read()         fopen.close()         tounicode=unicode(tempcontent,"gb2312","ignore")         toutf8=tounicode.encode("utf8")         import os.path         if (os.path.exists(rpth)==False):                 tempresultdir=os.mkdir(rpth)         else:                 pass         os.chdir(rpth)         tempresult=open("temp.txt",'w')         tempresult.write(toutf8)         tempresult.close()         f1=open(ipth,"r")         tempname=f1.readline(10)         print tempname         newname=tempname.rstrip()         print newname         f1.close()         os.rename("temp.txt",newname+".txt") root=Tk() B1=Button(root,text="input",width=30,height=2,command=inputpath).pack() B2=Button(root,text="OK",width=30,height=2,command=processfile).pack() B3=Button(root,text="Change Result Directory",width=30,height=2,command=chresultdir).pack() root.mainloop()

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档