Pyconv - Conversor de codificação de caracteres
Publicado por Fernando (última atualização em 22/08/2014)
[ Hits: 3.487 ]
Homepage: https://github.com/phoemur/
Este script foi escrito em Python 3 (necessita python >= 3.2) aos moldes da ferramenta iconv, que serve para converter a codificação de caracteres (UTF-8, ISO8859-1, ASCII etc.) de arquivos texto.
pyconv.py [-h] [-f CODING] [-t CODING] [-w] [-l] [-d]
[filename [filename ...]]
Convert encoding of given files from one encoding to another.
Positional arguments:
filename File to convert
Optional arguments:
-h, --help show this help message and exit
-f CODING, --from_code CODING
Encoding of original text
-t CODING, --to_code CODING
Encoding for output
-w, --write Make change to file in place
-l, --list List all known coded character sets
-d, --detect Detect file encoding
#!/usr/bin/env python3
import os
import sys
import codecs
import argparse
from encodings.aliases import aliases
parser = argparse.ArgumentParser(description="Convert encoding of given files from one encoding to another.")
parser.add_argument("filename", help="File to convert", nargs='*')
parser.add_argument("-f", "--from_code", metavar='CODING', help="Encoding of original text")
parser.add_argument("-t", "--to_code", metavar='CODING', help="Encoding for output")
parser.add_argument("-w", "--write", help="Make change to file in place", action="store_true")
parser.add_argument("-l", "--list", help="List all known coded character sets", action="store_true")
parser.add_argument("-d", "--detect", help="Detect file encoding", action="store_true")
args = parser.parse_args()
if args.list:
cod_set = set()
for k, v in aliases.items():
cod_set.add(k.upper())
cod_set.add(v.upper())
for elem in sorted(list(cod_set)):
print(elem)
sys.exit(0)
if not args.filename:
parser.print_help()
sys.exit(0)
if args.detect:
try:
import chardet
except ImportError:
print("Need to install chardet - https://pypi.python.org/pypi/chardet")
sys.exit(1)
for files in args.filename:
try:
with open(files, mode='rb') as fd:
content = chardet.detect(fd.read())
conf = (content['confidence'] * 100) or '?'
enc = content['encoding'] or '?'
print("File: {0:<25} Encoding: {1:<15} Confidence:{2:^5}%".format(files, enc, conf))
except OSError:
pass
sys.exit(0)
ORIG_CODING = args.from_code
DEST_CODING = args.to_code or sys.stdout.encoding
try:
sys.stdout = codecs.getwriter(DEST_CODING)(sys.stdout.detach())
except LookupError as err:
print(err)
sys.exit(1)
for files in args.filename:
try:
with open(files, mode='r', encoding=ORIG_CODING) as fh:
content = fh.read()
if args.write:
with open(files, mode='w', encoding=DEST_CODING) as fh2:
fh2.write(content)
else:
print(content)
except Exception as err:
print(err)
sys.exit(2)
Mini-dicionário de termos em Python e PyQT 4
IA Turbina o Desktop Linux enquanto distros renovam forças
Como extrair chaves TOTP 2FA a partir de QRCODE (Google Authenticator)
Linux em 2025: Segurança prática para o usuário
Desktop Linux em alta: novos apps, distros e privacidade marcam o sábado
Como usar Gpaste no ambiente Cinnamon
Atualizando o Fedora 42 para 43
Como saber se o seu e-mail já teve a senha vazada?
VOL já não é mais como antes? (9)
É normal não gostar de KDE? (13)
E aí? O Warsaw já está funcionando no Debian 13? [RESOLVIDO] (15)
Secure boot, artigo interessante, nada técnico. (4)
copiar library para diretorio /usr/share/..... su com Falha na a... (1)









