61 votes

Comment imprimer facilement un texte en ascii-art ?

J'ai un programme qui génère beaucoup de données, et Je veux qu'une partie de cette production soit vraiment remarquable. . Un moyen pourrait être de rendre un texte important avec de l'art ascii comme ce service web fait par exemple :

 #    #   ##   #####  #    # # #    #  ####  
 #    #  #  #  #    # ##   # # ##   # #    # 
 #    # #    # #    # # #  # # # #  # #      
 # ## # ###### #####  #  # # # #  # # #  ### 
 ##  ## #    # #   #  #   ## # #   ## #    # 
 #    # #    # #    # #    # # #    #  ####  

d'autres solutions pourraient être des sorties colorées ou en gras . Alors comment faire ce genre de choses facilement en Python ?

2 votes

Vous pourriez faire appel à figlet, un utilitaire Unix.

1 votes

@Marcin : merci, figlet semble sympa ! Certaines personnes semblent même avoir implémenté des wrappers python pour lui.

0 votes

Heureux d'aider. N'hésitez pas à répondre à votre propre question en fournissant des informations supplémentaires à ce sujet.

103voto

J.F. Sebastian Points 102961
  • pyfiglet - implémentation purement Python de http://www.figlet.org

    pip install pyfiglet
  • termcolor - fonctions d'aide pour le formatage des couleurs ANSI

    pip install termcolor
  • colorama - support multiplateforme (Windows)

    pip install colorama

    import sys

    from colorama import init init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected from termcolor import cprint from pyfiglet import figlet_format

    cprint(figlet_format('missile!', font='starwars'), 'yellow', 'on_red', attrs=['bold'])

Exemple

$ python print-warning.py 

missile

$ python print-warning.py | cat
.\_\_\_  \_\_\_.  \_\_       \_\_\_\_\_\_\_.     \_\_\_\_\_\_\_. \_\_   \_\_       \_\_\_\_\_\_\_  \_\_
|   \\/   | |  |     /       |    /       ||  | |  |     |   \_\_\_\_||  |
|  \\  /  | |  |    |   (----\`   |   (----\`|  | |  |     |  |\_\_   |  |
|  |\\/|  | |  |     \\   \\        \\   \\    |  | |  |     |   \_\_|  |  |
|  |  |  | |  | .----)   |   .----)   |   |  | |  \`----.|  |\_\_\_\_ |\_\_|
|\_\_|  |\_\_| |\_\_| |\_\_\_\_\_\_\_/    |\_\_\_\_\_\_\_/    |\_\_| |\_\_\_\_\_\_\_||\_\_\_\_\_\_\_|(\_\_)

34voto

jsheperd Points 55

La LIP offre un moyen très simple de le faire. Vous pouvez rendre le texte sur une image en noir et blanc et convertir ce bitmap en un flux de chaînes de caractères en remplaçant les pixels noirs et blancs par des caractères.

from PIL import Image, ImageFont, ImageDraw

ShowText = 'Python PIL'

font = ImageFont.truetype('arialbd.ttf', 15) #load the font
size = font.getsize(ShowText)  #calc the size of text in pixels
image = Image.new('1', size, 1)  #create a b/w image
draw = ImageDraw.Draw(image)
draw.text((0, 0), ShowText, font=font) #render the text to the bitmap
for rownum in range(size[1]): 
#scan the bitmap:
# print ' ' for black pixel and 
# print '#' for white one
    line = []
    for colnum in range(size[0]):
        if image.getpixel((colnum, rownum)): line.append(' '),
        else: line.append('#'),
    print ''.join(line)

Il rend le résultat suivant :

 #######                 ##                              #######   ##  ##
 ##   ###           ##   ##                              ##   ###  ##  ##
 ##    ##           ##   ##                              ##    ##  ##  ##
 ##    ## ##    ## ####  ######     ####    ######       ##    ##  ##  ##
 ##    ##  ##  ###  ##   ###  ##   ##  ##   ###  ##      ##    ##  ##  ##
 ##   ##   ##  ##   ##   ##   ##  ##    ##  ##   ##      ##   ##   ##  ##
 ######    ##  ##   ##   ##   ##  ##    ##  ##   ##      ######    ##  ##
 ##         ## #    ##   ##   ##  ##    ##  ##   ##      ##        ##  ##
 ##         ####    ##   ##   ##  ##    ##  ##   ##      ##        ##  ##
 ##         ####    ##   ##   ##   ##  ##   ##   ##      ##        ##  ##
 ##          ##     ###  ##   ##    ####    ##   ##      ##        ##  ########
             ##
             ##
           ###             
         ##
       ###

J'ai fait un exemple un peu plus complet avec un style fonctionnel.

import Image, ImageFont, ImageDraw

ShowText = 'Python PIL'

font = ImageFont.truetype('arialbd.ttf', 15) #load the font
size = font.getsize(ShowText)  #calc the size of text in pixels
image = Image.new('1', size, 1)  #create a b/w image
draw = ImageDraw.Draw(image)
draw.text((0, 0), ShowText, font=font) #render the text to the bitmap

def mapBitToChar(im, col, row):
    if im.getpixel((col, row)): return ' '
    else: return '#'

for r in range(size[1]):
    print ''.join([mapBitToChar(image, c, r) for c in range(size[0])])

10voto

Dave Rove Points 608

C'est amusant. J'ai trouvé comment utiliser PIL (le fork "Pillow", bien sûr) et Numpy pour faire cela de manière entièrement "vectorisée", c'est-à-dire sans boucles :

text = "Hi there"
from PIL import Image, ImageDraw, ImageFont
import numpy as np
myfont = ImageFont.truetype("verdanab.ttf", 12)
size = myfont.getsize(text)
img = Image.new("1",size,"black")
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, "white", font=myfont)
pixels = np.array(img, dtype=np.uint8)
chars = np.array([' ','#'], dtype="U1")[pixels]
strings = chars.view('U' + str(chars.shape[1])).flatten()
print( "\n".join(strings))

           ##           ##                            
 ##    ##  ##      ##   ##                            
 ##    ##          ##   ##                            
 ##    ##  ##     ##### #####    ####   ## ##  ####   
 ##    ##  ##      ##   ##  ##  ##  ##  ##### ##  ##  
 ########  ##      ##   ##  ##  ##  ##  ##    ##  ##  
 ##    ##  ##      ##   ##  ##  ######  ##    ######  
 ##    ##  ##      ##   ##  ##  ##      ##    ##      
 ##    ##  ##      ##   ##  ##  ##   #  ##    ##   #  
 ##    ##  ##       ### ##  ##   ####   ##     ####

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X