Pyconv - Conversor de codificação de caracteres

Publicado por Fernando (última atualização em 22/08/2014)

[ Hits: 3.152 ]

Homepage: https://github.com/phoemur/

Download pyconv.py




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

  



Esconder código-fonte

#!/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)

Scripts recomendados

Leitura de arquivo com input

Agenda PasPy

Le um arquivo e exibe na tela

Expressão regular com input STDIN

Exmaill - Extrator de Emails


  

Comentários
[1] Comentário enviado por snowbg em 22/04/2015 - 15:39h

Muito bom cara.

Nesse artigo também temos algumas dicas nesse sentido:

http://python3-dicas.blogspot.com/2015/04/conversoes-inteiro-hexadecimal-inteiro.html

Dentre outros do mesmo blog.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts