Geben Sie Farbzeichen mit Python zu hübsch aus

Überblick

Es gab einen Artikel über hübschen Farbdruck, und ich fragte mich, was ich mit Python machen sollte. Also suchte ich nach Teilen mit Stackoverflow und schrieb ihn, indem ich ihn nachahmte.

pp.png

Vorerst habe ich die Yaml-Datei gelesen und das Ergebnis der Analyse angezeigt.

Wie benutzt man

python pp.py <Dateiname>  [Anzahl der Einrückungen]

So was

pp.png

pp.py


# -*- coding: utf-8 -*-

class color:
    BLUE = '\033[1;34m'
    BLUEL = '\033[0;34m'
    GREEN = '\033[1;32m'
    GREENL = '\033[0;32m'
    CYAN = '\033[1;36m'
    CYANL = '\033[0;36m'
    RED = '\033[1;31m'
    REDL = '\033[0;31m'
    PURPLE = '\033[1;35m'
    PURPLEL = '\033[0;35m'
    YELLOW = '\033[1;33m'
    BROWN = '\033[0;33m'
    WHITE = '\033[1;37m'
    GRAYL = '\033[0;37m'
    GRAYD = '\033[1;30m'
    BLACK = '\033[0;30m'
    ENDC = '\033[0m'

def pretty_convert(obj):
    if isinstance(obj, (float)):
        return u'{1}{2}{0}'.format(color.ENDC, color.PURPLEL, obj)
    elif isinstance(obj, ( bool )):
        return u'{1}{2}{0}'.format(color.ENDC, color.CYAN, obj)
    elif isinstance(obj, ( int, long, complex )):
        return u'{1}{2}{0}'.format(color.ENDC, color.BLUE, obj)
    elif isinstance(obj, ( basestring )):
        return u'{1}"{0}{2}{3}{0}{1}"{0}'.format(color.ENDC, color.REDL, color.RED, obj)
    elif isinstance(obj, ( dict )):
        return dict((u'{1}{2}:{0}'.format(color.ENDC, color.YELLOW,k), pretty_convert(v)) for k, v in obj.items())
    elif isinstance(obj, (list, tuple)):
        return map(pretty_convert, obj)
    return obj

def walk_obj(buf, obj, indent_num=2, depth=0, eol='', wrap_len=60, wrap_total=100, lf='\n'):
    indent = ' '*indent_num*depth
    buf.write(u'{0}'.format(eol if not eol else eol+indent) )
    if isinstance(obj, (basestring, int, float, complex)):
        buf.write(u'{0}'.format(obj).replace(lf, '{0}{1} '.format(lf, indent)) )
    elif isinstance(obj, ( dict )):
        eol, eol_org = lf, eol
        buf.write('{ ')
        for key in obj.keys():
            buf.write(u'{0}{1}{2}{3} '.format(eol, indent, ' '*indent_num, key))
            walk_obj(buf=buf, obj=obj[key], indent_num=indent_num, depth=depth+1, eol='', wrap_len=wrap_len, lf=lf )
            buf.write(',')
        buf.write('{0}}}'.format(eol if not eol else eol+indent) )
        eol=eol_org
    elif isinstance(obj, (list, tuple)):
        eol_org, indent_org = eol, indent
        for item in obj:
            if isinstance(item, (list, dict)):
                eol = lf
                break
            else:
                eol = ''
                indent = ''
                continue
        if max(map(len,obj)) > wrap_len or sum(map(len,obj)) > wrap_total:
            eol = lf
        buf.write('[ ')
        for item in obj:
            walk_obj(buf=buf, obj=item, indent_num=indent_num, depth=depth+1, eol=eol, wrap_len=wrap_len, lf=lf )
            buf.write(', ')
        buf.write('{0}]'.format(eol if not eol else eol+indent_org) )
        eol, indent = eol_org, indent_org
    if depth == 0:
        buf.write(lf)

def pretty_print(obj, indent=2, b=None):
    if not b:
        import sys, codecs
        b = codecs.getwriter('utf_8')(sys.stdout)
    walk_obj(b, pretty_convert(obj), indent_num=indent)


if __name__ == '__main__':
  import sys
  import codecs
  import yaml
  import pprint

  if len(sys.argv) < 2:
     print 'yaml file name is needed'
     sys.exit(2)
  indent = 2 if len(sys.argv) <3 else int(sys.argv[2])

  sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

  file = codecs.open(sys.argv[1], 'r', 'utf_8').read()

  sys.stdout.write('# file \n\n```\n')
  sys.stdout.write(file)

  contents = yaml.load(file)

  sys.stdout.write('\n```\n\n# pprint.PrettyPrinter \n\n```\n\n')
  pp=pprint.PrettyPrinter(indent=indent)
  pp.pprint(contents)

  sys.stdout.write('\n```\n\n# pretty_print \n\n```\n')
  pretty_print(contents, indent, sys.stdout)
  sys.stdout.write('\n')

zz.yml


dictionary:
  - { test: this is test, test2: 1, test3: true }
  - [1,2,3,4,5]
 ―――― 'Mit Japanern spielen'
 - [6,7,8,9, "Test"]
  - name: test
 Name: test2
  - test2
  - test3
  - true
  - 65535
  - 3.14
  - - list1
    - list2
    - list3
list:
  -  name: this is dictionary,
     bool: false
     int: 15000
     float: 15.6
     list: [ 0,1,2,3,4 ]
  - "this is test"
  - |
    this is test
    this is Test
    this is tesT

Recommended Posts

Geben Sie Farbzeichen mit Python zu hübsch aus
Ausgabe in eine CSV-Datei mit Python
Versuchen Sie, Farbfilme mit Python zu reproduzieren
Python-Protokoll mit GAE an die Konsole ausgeben
Segfo Python mit 33 Zeichen
Ich habe versucht, LLVM IR mit Python auszugeben
So löschen Sie die von Python ausgegebenen Zeichen
[Python] Umgang mit japanischen Zeichen mit openCV
Stellen Sie mit Python eine Verbindung zu BigQuery her
Prozedur zum Laden von MNIST mit Python und zur Ausgabe an png
Probieren Sie die Python-Ausgabe mit Haxe 3.2 aus
Stellen Sie mit Python eine Verbindung zu Wikipedia her
Post to Slack mit Python 3
Hübscher Druck json oder yaml mit Farbe in Python
Schalten Sie Python mit Alternativen auf 2.7 um
Schreiben Sie mit Python in csv
[Python-pptx] Gibt PowerPoint-Schriftinformationen mit Python in CSV aus
Link, um mit Python zu beginnen
Schön dich mit Python zu treffen
Versuchen Sie, Facebook mit Python zu betreiben
Eingabe / Ausgabe mit Python (Python-Lernnotiz ⑤)
Konvertieren Sie die Liste mit Python in DataFrame
MP3 → WAV-Konvertierung mit Python
Schwanzrekursion mit Python2 durchführen
Erste Schritte mit Python
[Hinweis] Hallo Weltausgabe mit Python
Unit Test Log Ausgabe mit Python
Was tun mit PYTHON Release?
[Python] Einzeilige Starlin-Sortierung mit 50 Zeichen
So berechnen Sie das Datum mit Python
Mit Python 3 einfach auf Twitter posten
Versuchen Sie, Audio mit M5 STACK auszugeben
Ich möchte mit Python debuggen
Konvertieren Sie in eine Zeichenfolge, während Sie die Standardausgabe mit dem Python-Unterprozess ausgeben
Ich möchte den Anfang des nächsten Monats mit Python ausgeben
Geben Sie den Inhalt von ~ .xlsx im Ordner mit Python in HTML aus
[Python] Versuchen Sie, Zeichen aus Bildern mit OpenCV und pyocr zu erkennen
Ändern Sie die Python 64-Bit-Umgebung mit Anaconda in eine 32-Bit-Umgebung
Englische Spracherkennung mit Python [Rede zu Text]
Konvertieren Sie Memos sofort mit Python 2to3
HTML-Mail mit Bild zum Senden mit Python
Python nur mit Hallo, Welten zu erinnern
Einführung in das Auffüllen von Python-Bildern Auffüllen von Bildern mit ImageDataGenerator
Konvertieren Sie Excel-Daten mit Python in JSON
Konvertiere Hiragana mit Python (Beta) in Romaji
Fraktal zum Erstellen und Spielen mit Python
Ich wollte ABC160 mit Python lösen
Stellen Sie mit Python in Docker eine Verbindung zu MySQL her
So arbeiten Sie mit BigQuery in Python
[Einführung in Python] Verwenden wir foreach mit Python
Einzelpixel-Kamera zum Erleben mit Python
Ich möchte Protokolle mit Python analysieren
Wie man einen Taschentest mit Python macht
Ich möchte mit aws mit Python spielen