txt文本转编码格式(支持utf-8、GBK、GB2312、GB18030、BIG5等所有编码格式)

txt文本转编码格式(支持utf-8、GBK、GB2312、GB18030、BIG5等所有编码格式)

脚本的使用方法

创建一个convert_to_utf8的python文件,将代码复制保存。
在终端输入以下命令,即可实现自动检测原文件的编码格式,并生成对应的新文件:

python convert_to_utf8.py 原文件.txt 新文件.txt

当然,也可以指定原文件的编码格式:

python convert_to_utf8.py 原文件.txt 新文件.txt --encoding Big5 
import argparse
import chardet

def detect_encoding(file_path):
    """Detect the encoding of a file."""
    with open(file_path, 'rb') as file:
        raw_data = file.read(10000)  # Read enough of the file to detect encoding
        result = chardet.detect(raw_data)
        print(f"Detected encoding: {result['encoding']} with confidence {result['confidence']}")
        return result['encoding']

def convert_to_utf8(input_file, output_file, encoding=None):
    """Convert a file to UTF-8 encoding using a specified or detected encoding."""
    if not encoding:
        encoding = detect_encoding(input_file)

    try:
        with open(input_file, 'r', encoding=encoding, errors='ignore') as file:
            content = file.read()

        with open(output_file, 'w', encoding='utf-8') as file:
            file.write(content)

        print(f"文件已成功转换并保存为:{output_file},使用的编码:{encoding}")
    except Exception as e:
        print(f"转换过程中发生错误:{e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Convert text file encoding to UTF-8 using a specified or detected encoding.")
    parser.add_argument("input_file", help="The path to the input file.")
    parser.add_argument("output_file", help="The path to the output file where the UTF-8 encoded file will be saved.")
    parser.add_argument("--encoding", help="Optionally specify the encoding to override automatic detection.", default=None)
    args = parser.parse_args()

    convert_to_utf8(args.input_file, args.output_file, args.encoding)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值