[Python] `rich`

Python `rich`

About `rich`

rich is a python library to visualize data, create a simple 2D grid or print characters at specific position for terminal-based projects.

rich allows to:
  • format text with colors and styles
  • build tables and layouts
  • print Unicode and emoji
  • draw structured output in the terminal

Example

import requests
from bs4 import BeautifulSoup
from rich.console import Console

import requests
from bs4 import BeautifulSoup
from rich.console import Console

def reveal_words(url: str):
  response  = requests.get(url)
  soup = BeautifulSoup(response.content, 'html.parser')
  rows = soup.select('tr')[1:] # remove the header
  data = []
  # data = [(93, 5, '░'), (2, 5, '░'), (8, 0, '░'), (39, 1, '█'), (64, 0, '░'), (63, 1, '█'), (84, 3, '█'), (9, 4, '█'), (55, 1, '█'), (23, 4, '█'), (91, 5, '█'), (21, 5, '█'), (79, 1, '░'), (65, 1, '░'), (52, 5, '█'), (49, 5, '░'), (24, 1, '░'), (42, 5, '░'), (6, 3, '█'), (24, 2, '░'), (0, 4, '█'), (65, 3, '█'), (74, 5, '░'), (36, 6, '░'), (22, 1, '█'), (62, 3, '░'), (24, 5, '░'), (58, 5, '█'), (35, 6, '█'), (55, 3, '░'), (20, 0, '█'), (88, 3, '█'), (46, 6, '█'), (8, 5, '█'), (13, 1, '█'), (76, 4, '█'), (54, 1, '█'), (2, 0, '█'), (91, 4, '█'), (34, 6, '█'), (80, 0, '█'), (12, 5, '█'), (14, 3, '░'), (1, 2, '█'), (67, 5, '░'), (93, 1, '░'), (48, 5, '█'), (79, 0, '█'), (13, 5, '█'), (39, 5, '█'), (48, 6, '░'), (12, 3, '█'), (92, 5, '█'), (52, 4, '█'), (55, 2, '░'), (61, 5, '░'), (66, 4, '█'), (7, 6, '█'), (83, 4, '█'), ...]
  for row in rows:
    x = int(row.select('td')[0].get_text())
    y = int(row.select('td')[2].get_text())
    char = row.select('td')[1].get_text()

    data.append((x, y, char))

  console = Console()
  width = max(datum[0] for datum in data) + 1
  height = max(datum[1] for datum in data) + 1

  grid = []
  for _ in range(height + 1):
    temp = []
    for _ in range(width + 1):
      temp.append(' ')
    grid.append(temp)

  for x, y, char in data:
    if 0 <= x < width and 0 <= y < height:
      grid[height-y][x] = char

  for row in grid:
    console.print(''.join(row))

reveal_words(url_target)

This example is to draw letters based on (x, y) coordinates with Unicode characters retrieved from a link.

First, from a link, the data of coordinates and Unicode are made into a list of tuple
Second, am empty grid is made, using rich, the space letters matched with the coordinates in the list are replaced with their designated letters.

The point is that the grid is made of nested list, whose (0, 0) is located on the top left side. The grid expands to the right and downwards. The coordinates from the link are different: its (0, 0) is at the left bottom and the grid expands to the right but upwards. This requires to modify y coordinates when replacing the letters by subtracting the y coordinates from the height of the grid.


Comments