欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Python批量對文本文件編碼互轉(zhuǎn)的方法

 更新時(shí)間:2023年03月24日 15:51:04   作者:Biem  
這篇文章主要介紹了使用Python批量對文本文件編碼互轉(zhuǎn)的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

在Windows下寫C語言默認(rèn)是GB2312,放到Linux上就會亂碼,因?yàn)長inux和MacOS默認(rèn)是UTF-8,因此寫了個(gè)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('''!??!在轉(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ù)錯(cuò)誤,請把要轉(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)的方法的文章就介紹到這了,更多相關(guān)Python批量轉(zhuǎn)換文本文件編碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論