栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

批量转化GBK编码至UTF-8编码工具【Python】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

批量转化GBK编码至UTF-8编码工具【Python】

批量转化GBK编码至UTF-8编码工具

github地址

安装 pip安装
pip install utf8conv
二进制文件下载

github 发布

使用
参数说明
-i / --input输入文件或者文件目录
-o / --output_folder输出目录
-s / --suffix需要转化的文件后缀名,如: .txt .json .c .py 等
-v / --verbose输出详细处理文件
-h / --help参数说明
python调用
# 帮助
python -m utf8conv -h

# 基本使用
python -m utf8conv -i 输入文件/目录 -o 输出目录 -t 格式列表

# 使用示例,转化code 目录下 .txt .json .c .cpp .py 为utf-8 格式
python -m utf8conv 
	-i /root/code 
	-o /root/code_u8 
	-s .txt .json .c .cpp .py
	
	
# 转化文本文件
python -m utf8conv -i /root/code/abc.cpp -o ./
二进制文件参考上述参数 源码内容
import argparse
from pathlib import Path
import chardet
from tqdm import tqdm
import shutil
from time import time

parser = argparse.ArgumentParser(description='convert file to utf-8 encoding')
parser.add_argument('-i', '--input', help='input a folder or a single_file')
parser.add_argument('-o', '--output_folder', help='output folder for converted files')
parser.add_argument('-s', '--suffix', nargs='+', help='file type list. eg.: .txt .c .json .py .', default=['.txt'])
parser.add_argument('-v', '--verbose', action='store_true', help='show details')
args = parser.parse_args()

st = time()

file_suffix = set([t.lower() for t in args.suffix])

# get file list
proc_file_list = [Path(args.input).resolve()] 
    if Path(args.input).is_file() 
    else [file.resolve() for file in Path(args.input).rglob('*') if file.suffix.lower() in file_suffix]

# to maintain the tree structure, get the max same depth of input folder
max_depth = len(str(proc_file_list[0].parent)) + 1 
    if len(proc_file_list) == 1 
    else len(str(max(set.intersection(*map(set, [[p for p in f.parents] for f in proc_file_list]))))) + 1

num_file = len(proc_file_list)
if not args.verbose:
    proc_file_list = tqdm(proc_file_list)

for n, f in enumerate(proc_file_list):
    target_path = Path(args.output_folder) / str(f)[max_depth:]
    if not target_path.parent.is_dir():
        target_path.parent.mkdir(parents=True)
    with open(f, 'rb') as file:
        # using chardet lib to detect text encoding
        det = chardet.detect(file.read())
        det_encoding = det['encoding'].upper() if det['encoding'] is not None else 'UTF-8'
    coding = 'GBK' if 'GB' in det_encoding else det_encoding

    # cov other encoding text into utf-8, copy utf-8 to target folder
    if coding != 'UTF-8':
        with open(f, 'r', encoding=coding) as file:
            txt = file.read()
        with open(target_path, 'w+', encoding='utf-8') as file:
            file.write(txt)
    else:
        shutil.copyfile(f, target_path)

    if args.verbose:
        print(' %.2f%% - [%i/%i] - %s - saved file <%s> to <%s>' %
              ((n + 1) / num_file * 100,
               n + 1, num_file,
               det_encoding,
               str(f.resolve()),
               str((Path(args.output_folder) / str(f)[max_depth:]).resolve())
               ))
if args.verbose:
    print('========================================')
    print('spend time: %s s' % (time()-st))


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980111.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号