[python]将txt文件编批量转为utf8

[python]将txt文件编批量转为utf8

因为处理数据的需求,所以txt文件编码需要统一为utf8,windows下txt文件编码格式多为gbk。

1.基本思路

整个过程基本分为以下几个步骤,也是该脚本的主体思路

  1. 获取需要改变编码格式的文件夹路径
  2. 读取该文件夹下的txt文件,利用第三方库chardet预测编码,并将该编码格式记录
  3. 将该txt文件按预测的编码格式解码后,用utf8重新编码,重新写入源文件并覆盖,实现转码
  4. 对每一个文件重复2-3步骤,直到所有的txt都被重新编码

2.一些题外话

1. 由于事先所接收的文件编码格式多且杂乱,所以需要通过chardet预测,如预测出现问题则可能导致解码错误,重新写入时会出现乱码现象,至今未曾解决,但该bug出现频率不高,常见于文本量极小的中文文件。
2. chardet 不能精确到gb2312,所以预测结果为gb2312时,需要将其归为GBK,gb2312也确实属于GBK的子集。
3. 预测结果为utf8的文本直接不作处理
4.主体思路应该为对单个文件的预测,解码,重新编码,即gbk_2_utf8这个方法(原来的目的和实现的目标是gbk转utf8,后来编码时发现可以实现更为强大的功能,方法名就没改)。为了方便使用,套了一层循环使用的外壳,实现对某个路径下所有txt文件的预测,解码,重新编码。另外顺便加了一个可以获取路径的超超超超超简陋gui界面。

3.源码如下 || Talk is cheap,show me the code!

import os
import codecs
import chardet
import time
from tkinter import *
from tkinter.filedialog import askdirectory
from tkinter import messagebox

检验文本文件的编码格式并转为utf-8

def gbk_2_utf8(filename,out_enc="UTF-8"):
    try:
        content = open(filename, 'rb').read()
        source_encoding = chardet.detect(content)
        print("编码格式: " + source_encoding['encoding'])

        if(source_encoding['encoding'] != "utf-8"):
            if(source_encoding['encoding'] == 'GB2312'):
                content = content.decode("GBK")
                content = content.encode(out_enc)
                codecs.open(filename, 'wb').write(content)
            else:
                content = content.decode(source_encoding['encoding']).encode(out_enc)
                codecs.open(filename, 'wb').write(content)
            print("转换完成")
            print("*************************")
        else:
            print("无需转换")
            print("*************************")

    except IOError as err:
        print("I/O error:{0}".format(err))

遍历文件夹下的所有txt文件

 - def explore(dir):
       for root, dirs, files in os.walk(dir):
           for file in files:
               if os.path.splitext(file)[1] == '.txt':
                   print("打开文件:"+file)
                   path = os.path.join(root, file)
                   #print(path)
                   gbk_2_utf8(path)
   				
   # 获取从外部选择的文件夹路径 def getpath():
       def selectPath():
           path_ = askdirectory()
           path.set(path_)
       root = Tk()
       path = StringVar()
       def close():
           if(path.get() == ""):
               messagebox.showinfo(" ","没有选择路径")
           else:
               root.withdraw()
               root.quit()
       Label(root, text="目标路径:").grid(row=0, column=0)
       Entry(root, textvariable=path).grid(row=0, column=1)
       Button(root, text="路径选择", command=selectPath).grid(row=0, column=2)
       Button(root, text="确定", command=close).grid(row=0, column=3)
       root.mainloop()
       return path.get()
   
   def main():
       path = getpath()
       print("选择的路径为: " + path)
       print("*************************")
       explore(path)
       print("转换完成3秒后结束")
       time.sleep(1)
       print("转换完成2秒后结束")
       time.sleep(1)
       print("转换完成1秒后结束")
       time.sleep(1)
       print("转换完成,准备退出")
   
   
   if __name__ == "__main__":
       main()

下载地址

提供一个可以在未安装环境的windows系统下运行的版本
链接:https://pan.baidu.com/s/1gHvSLtutC41yjYrqMAHRfA 密码:uaw9

原文作者: Za_Nks
原文链接: https://www.zanks.cn/python/python-将txt文件编批量转为utf8.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!

----------------------------本文结束 感谢您的阅读---------------------------

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为你讲解如何使用Pythontxt文件批量转为JSON。 假设你有多个txt文件,它们的文件名都以.txt结尾,你想将它们批量转换为JSON格式并保存在同一目录下。具体的步骤如下: 1. 导入必要的模块 首先,需要导入os和json模块。os模块提供了访问操作系统功能的接口,json模块提供了处理JSON格式的函数。 ``` import os import json ``` 2. 遍历txt文件 使用os模块的listdir函数遍历存储txt文件的目录。然后,使用Python的for循环来迭代目录中的每个文件,找到以.txt结尾的文件,并对它们进行操作。在循环中,使用os.path.join函数创建文件的完整路径。 ``` txt_folder = "/path/to/txt/folder" # 存储txt文件的目录 json_folder = "/path/to/json/folder" # 存储json文件的目录 for file_name in os.listdir(txt_folder): if file_name.endswith(".txt"): txt_path = os.path.join(txt_folder, file_name) ``` 3. 读取txt文件并转换为JSON格式 对于每个txt文件,使用Python的with语句打开文件并读取其内容。然后,使用json模块的loads函数将其转换为Python中的字典类型。 ``` with open(txt_path, 'r') as file: text = file.read() data = json.loads(text) ``` 4. 将Python字典转换为JSON格式 使用json模块的dumps函数将Python字典转换为JSON格式。 ``` json_data = json.dumps(data) ``` 5. 保存JSON文件 将JSON数据写入名为file_name.json的文件中,并将其保存在json_folder中。可以使用Python内置的open函数打开一个新文件,并使用write函数将JSON数据写入该文件。 ``` json_path = os.path.join(json_folder, file_name.replace(".txt", ".json")) with open(json_path, 'w') as file: file.write(json_data) ``` 最终的完整代码如下: ``` import os import json txt_folder = "/path/to/txt/folder" # 存储txt文件的目录 json_folder = "/path/to/json/folder" # 存储json文件的目录 for file_name in os.listdir(txt_folder): if file_name.endswith(".txt"): txt_path = os.path.join(txt_folder, file_name) with open(txt_path, 'r') as file: text = file.read() data = json.loads(text) json_data = json.dumps(data) json_path = os.path.join(json_folder, file_name.replace(".txt", ".json")) with open(json_path, 'w') as file: file.write(json_data) ``` 希望这个代码可以帮助到你。如果还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值