溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用Python批量對文本文件編碼互轉(zhuǎn)

發(fā)布時間:2023-04-18 13:59:16 來源:億速云 閱讀:275 作者:iii 欄目:編程語言

這篇文章主要介紹“怎么使用Python批量對文本文件編碼互轉(zhuǎn)”,在日常操作中,相信很多人在怎么使用Python批量對文本文件編碼互轉(zhuǎn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”怎么使用Python批量對文本文件編碼互轉(zhuǎn)”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

在Windows下寫C語言默認(rèn)是GB2312,放到Linux上就會亂碼,因為Linux和MacOS默認(rèn)是UTF-8,因此寫了個Python小腳本對指定路徑下的文件進(jìn)行轉(zhuǎn)換。

from sys import argv
import os
from chardet import detect
from codecs import lookup

CONFIG_FILE = '.any2any'
DEFAULT_CONFIG = '''
.c
.h
.cpp
.hpp
.hxx
.cc
.cxx
.C
.c++
.m
.cs
.rs
.java
.kt
.php
.pm
.pl
.py
.sh
.go
.xml
.htm
.html
.css
.js
.jsx
.vue
.txt
.csv
'''

if os.path.exists(CONFIG_FILE):
    with open(CONFIG_FILE, 'r') as config_file:
        file_extension = tuple(config_file.read().split())
else:
    file_extension = tuple(DEFAULT_CONFIG.split())
print(f"將轉(zhuǎn)換 {' '.join(list(file_extension))}")


def bytes_encoding(b: bytes, length: int = 1024) -> str:
    '''
    返回探測到的編碼格式
    '''
    return detect(b[:length])['encoding']


def any2any(b: bytes, encoding: str) -> bytes:
    '''
    任意編碼字節(jié)轉(zhuǎn)換為任意編碼字節(jié)

    探測輸入的字節(jié)編碼格式,轉(zhuǎn)換為指定編碼,并返回對應(yīng)字節(jié)
    '''
    file_encoding = bytes_encoding(b)
    if file_encoding == encoding:
        return b
    return lookup(encoding).encode(lookup(file_encoding).decode(b)[0])[0]


def allfileset(path: str = '.', filepathset: set = set()) -> set:
    '''
    遞歸路徑下所有文件,返回絕對路徑集合
    '''
    if os.path.isdir(path):
        for item in os.listdir(path):
            filepath = os.path.join(path, item)
            if os.path.isfile(filepath):
                filepathset.add(os.path.abspath(filepath))
            else:
                allfileset(filepath, filepathset)
    else:
        filepathset.add(os.path.abspath(path))
    return filepathset


def is_valid_inputs() -> bool:
    '''
    檢查參數(shù)是否輸入正確
    '''
    return len(argv) > 1 and all(map(os.path.exists, argv[1:]))


def is_valid_encoding(encoding: str) -> bool:
    '''
    檢查是否存在指定編碼
    '''
    try:
        lookup(encoding)
        return True
    except:
        return False


def choice_encoding() -> str:
    choice = input('''?。。≡谵D(zhuǎn)換前注意備份文件?。。?
要轉(zhuǎn)換到什么編碼?
1. GB18030(Windows下常用,C語言不會亂碼)
2. UTF-8(非Windows下通用,例如Linux和macOS)
3. 其他
> ''')
    if choice == '1':
        return 'GB18030'
    elif choice == '2':
        return 'UTF-8'
    elif choice == '3':
        choice = input('輸入你想轉(zhuǎn)換到的編碼:')
        while not is_valid_encoding(choice):
            choice = input('不存在該編碼,重新輸入:')
        return choice
    else:
        print('不做任何操作')
        exit()


def main():
    if is_valid_inputs():
        encoding = choice_encoding()
        filepathset = set()
        for path in argv[1:]:
            filepathset.union(filter(lambda s: s.endswith(file_extension), allfileset(path, filepathset)))
        if filepathset:
            for path in filepathset:
                with open(path, 'rb') as f:
                    filebytes = any2any(f.read(), encoding)
                with open(path, 'wb') as f:
                    f.write(filebytes)
                print(f'{path} 已轉(zhuǎn)換到 {encoding}')
            print('轉(zhuǎn)換已完成')
        else:
            print('沒有任何可以轉(zhuǎn)換的文件,請檢查程序下是否有.any2any配置文件,用空格或換行間隔要轉(zhuǎn)換的文件類型,例如 .c .cpp .cs')
    else:
        print("未收到任何要轉(zhuǎn)換的文件或文件夾路徑,或參數(shù)錯誤,請把要轉(zhuǎn)換的文件或文件夾拖動到程序上。")

if __name__ == "__main__":
    try:
        main()
    finally:
        input('按任意鍵退出...')

可以使用pyinstaller打包成可執(zhí)行文件,帶著走或者分享給其他人用

安裝pyinstaller

conda install pyinstaller

打包Python文件,其中-i參數(shù)可以給.exe文件加上圖標(biāo),-F參數(shù)指定要打包的腳本

pyinstaller -i icon.ico -F any2any.py

最后打包好的可執(zhí)行文件在dict路徑下。

到此,關(guān)于“怎么使用Python批量對文本文件編碼互轉(zhuǎn)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI