當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python TextTable用法及代碼示例


它是一個Python模塊,可以幫助我們在終端上打印表格。它是用於以 ASCII 代碼讀寫文本表的基本 Python 模塊之一。它的目的是使接口盡可能相似,例如數據集Python 中的模塊。這文本表模塊支持固定大小的表(其中列大小是預先確定的)和dynamic-size表(其中可以添加或刪除列)。

安裝:

pip install texttable

分步方法:

  • 導入所需的模塊。

Python3


# Import required module 
import texttable
  • 創建一個對象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
  • 采用set_cols_align()方法 創建列。

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 
  • 采用set_cols_dtype()設置每列的數據類型。但是,此步驟是可選的。

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 
  • 采用set_cols_valign()調整列。

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         
  • 采用add_rows()向表中插入行的方法

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 
  • 采用draw()顯示表格的方法。

Python3


print(tableObj.draw()) 

表格說明如下:

下麵是基於上述方法的程序:

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()) 

輸出:



相關用法


注:本文由純淨天空篩選整理自佚名大神的英文原創作品 TextTable module in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。