Pyconv - Conversor de codificação de caracteres
Publicado por Fernando (última atualização em 22/08/2014)
[ Hits: 3.562 ]
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)
LazyDocker – Interface de Usuário em Tempo Real para o Docker
Instalando COSMIC no Linux Mint
Turbinando o Linux Mint: o poder das Nemo Actions
Inteligência Artificial no desenvolvimento de software: quando começar a usar?
O widget do Plasma 6 Área de Notificação
[Resolvido] Algo deu errado ao abrir seu perfil
Quando vocês pararam de testar distros? (14)
Problema com som no laptop (3)
Não estou conseguindo fazer funcionar meu Postfix na versão 2.4 no Deb... (2)









