Módulo TextTable en Python

Es un módulo de python, que nos ayuda a imprimir la tabla en la terminal. Es uno de los módulos básicos de Python para leer y escribir tablas de texto en código ASCII. Su objetivo es hacer que la interfaz sea lo más similar posible al  módulo csv en Python. El módulo de tabla de texto admite tablas de tamaño fijo (donde los tamaños de columna están predeterminados) y tablas de tamaño dinámico (donde se pueden agregar o quitar columnas).

Instalación:

pip install texttable

Enfoque paso a paso:

  • Importar módulo requerido.

Python3

# Import required module
import texttable
  • Crea un objeto de texttable()

Python3

# Creating object
tableObj = texttable.Texttable(self,max width)
  
# max_width must be an integer,whose value is maximum width of the table
# if set to 0, size is unlimited (self adjustible according to text inside cell),
# therefore cells won't be wrapped so it's recommended to use 0
  • Utilice el método set_cols_align() para crear columnas.

Python3

# Creating columns
tableObj.set_cols_align(["l", "l", "r", "c"])
  
# Set the desired columns alignment:
# "l" refers to column flushed left
# "c" refers to  column centered
# "r" refers to column flushed right
  • Use set_cols_dtype() para establecer el tipo de datos de cada columna. Sin embargo, este paso es opcional.

Python3

# Set datatype
tableObj.set_cols_dtype(["t", "i", "f", "a"])
  
# texttable objects supports five types of data types:
# "t" refers to text
# "f" refers to decimal
# "e" refers to exponent
# "i" refers to integer
# "a" refers to automatic
  • Use set_cols_valign() para ajustar las columnas.

Python3

# Adjust Columns
tableObj.set_cols_valign(["t", "t", "m", "b"])
  
# Set the desired columns vertical alignment the elements of the 
# array should be either "t", "m" or "b":
# "t" refers to column aligned on the top of the cell
# "m" refers to column aligned on the middle of the cell
# "b" refers to column aligned on the bottom of the cell        
  • Use el método add_rows() para insertar filas en la tabla

Python3

# Adding rows
table.add_rows([
        ["Text_Heading", "Int_Heading", "Float_Heading", "Auto_Heading"],
        ["Data1", 9, 1.23456789, "GFG"],
        ["Data2", 1, 9.87654321, "g4g"],
        ])
  
# add_rows(self, rows, header=True):
# The 'rows' argument can be either an iterator returning arrays, or a
# by-dimensional array.
# 'header' specifies if the first row should be used as the header of the table
  • Utilice el método draw() para mostrar la tabla.

Python3

print(tableObj.draw())

La ilustración de la tabla sería algo así:

A continuación se muestra un programa basado en el enfoque anterior:

Python3

# Import required module
import texttable
  
# Create texttable object
tableObj = texttable.Texttable()
  
# Set columns
tableObj.set_cols_align(["l", "r", "c"])
  
# Set datatype of each column
tableObj.set_cols_dtype(["a", "i", "t"])
  
# Adjust columns
tableObj.set_cols_valign(["t", "m", "b"])
  
# Insert rows
tableObj.add_rows([
        ["ORGANIZATION", "ESTABLISHED", "CEO"],
        ["Google", 1998, "Sundar Pichai"],
        ["Microsoft", 1975, "Satya Nadella"],
        ["Nokia", 1865, "Rajeev Suri"],
        ["Geeks for Geeks", 2008, "Sandeep Jain"],
        ["HackerRank", 2007, "Vivek Ravisankar"]
        ])
  
# Display table
print(tableObj.draw())

Producción:

Publicación traducida automáticamente

Artículo escrito por akshaypawar4 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *