杰瑞科技汇

Python PrettyTable如何美化表格输出?

Of course! The prettytable library in Python is a fantastic tool for creating simple, ASCII-based tables in the terminal. It's incredibly easy to use and perfect for displaying data in a clean, readable format, such as reports, database query results, or configuration data.

Python PrettyTable如何美化表格输出?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from basic usage to advanced features.


Installation

First, you need to install the library. It's available on PyPI, so you can install it using pip:

pip install prettytable

Basic Usage

The core idea is to create a PrettyTable object, add columns (optional, but good practice), and then add rows of data.

Example 1: The Simplest Way

You can just add rows, and prettytable will automatically figure out the column names.

Python PrettyTable如何美化表格输出?-图2
(图片来源网络,侵删)
from prettytable import PrettyTable
# Create a table object
table = PrettyTable()
# Add rows of data
table.add_row(["Alice", 24, "Engineer"])
table.add_row(["Bob", 30, "Doctor"])
table.add_row(["Charlie", 28, "Artist"])
# Print the table
print(table)

Output:

+---------+-----+----------+
|  Alice  | 24  | Engineer |
+---------+-----+----------+
|   Bob   | 30  |  Doctor  |
+---------+-----+----------+
| Charlie | 28  |  Artist  |
+---------+-----+----------+

Example 2: Adding Columns First (Recommended)

For more control over the order and alignment of columns, it's better to define them first.

from prettytable import PrettyTable
# Create a table object
table = PrettyTable()
# Define the column names
table.field_names = ["Name", "Age", "City"]
# Add rows of data
table.add_row(["David", 35, "New York"])
table.add_row(["Eve", 29, "London"])
table.add_row(["Frank", 42, "Tokyo"])
# Add a title to the table
table.title = "User Information"
# Print the table
print(table)

Output:

+-------------------------+
|      User Information   |
+---------+-----+----------+
|   Name  | Age |   City   |
+---------+-----+----------+
|  David  |  35 | New York |
|   Eve   |  29 |  London  |
|  Frank  |  42 |  Tokyo   |
+---------+-----+----------+

Common Formatting Options

prettytable offers a wide range of options to customize your table's appearance.

a. Column Alignment

You can align columns to the left (l), right (r), or center (c). The default is usually center.

table.align["Name"] = "l"  # Left-align the 'Name' column
table.align["Age"] = "r"   # Right-align the 'Age' column
table.align["City"] = "c"  # Center-align the 'City' column (default)
print(table)

Output:

+-------------------------+
|      User Information   |
+---------+-----+----------+
| Name    | Age |   City   |
+---------+-----+----------+
| David   |  35 | New York |
| Eve     |  29 |  London  |
| Frank   |  42 |  Tokyo   |
+---------+-----+----------+

b. Setting Column Widths

You can set a maximum width for a column. If the content is too long, it will be truncated.

table.max_width["City"] = 5 # Truncate city names to 5 characters
print(table)

Output:

+-------------------------+
|      User Information   |
+---------+-----+---------+
| Name    | Age |  City   |
+---------+-----+---------+
| David   |  35 |  New Y |
| Eve     |  29 |  Londo |
| Frank   |  42 |  Tokyo |
+---------+-----+---------+

c. Adding a Header Separator

You can add a line separator between the header and the rest of the table.

table = PrettyTable()
table.field_names = ["Product", "Price", "In Stock"]
table.add_row(["Laptop", "$1200", 10])
table.add_row(["Mouse", "$25", 50])
table.add_row(["Keyboard", "$75", 30])
table.add_row_separator() # Add a separator here
table.add_row(["Monitor", "$300", 15])
print(table)

Output:

+-----------+--------+----------+
|  Product  | Price  | In Stock |
+-----------+--------+----------+
|  Laptop   | $1200  |    10    |
|   Mouse   |  $25   |    50    |
| Keyboard  |  $75   |    30    |
+-----------+--------+----------+
|  Monitor  | $300   |    15    |
+-----------+--------+----------+

d. Hiding the Table Header

You can hide the header row if you don't need it.

table = PrettyTable()
table.field_names = ["Fruit", "Color"]
table.add_row(["Apple", "Red"])
table.add_row(["Banana", "Yellow"])
table.header = False
print(table)

Output:

+--------+--------+
|  Fruit | Color  |
+--------+--------+
| Apple  |  Red   |
| Banana | Yellow |
+--------+--------+

(Note: The header = False attribute hides the label row, but the data is still formatted as if it were there. This is a bit of a quirky behavior. For a true "no header" table, you might need to manipulate the output string.)


Loading Data from Other Sources

A common use case is loading data from a list of lists, a list of dictionaries, or even a CSV file.

a. From a List of Lists

You can add all rows at once using add_rows().

from prettytable import PrettyTable
data = [
    ["ID", "Name", "Score"],
    [1, "John Doe", 95],
    [2, "Jane Smith", 88],
    [3, "Peter Jones", 92]
]
table = PrettyTable()
table.add_rows(data)
print(table)

b. From a List of Dictionaries

This is very powerful, especially when dealing with data from APIs or databases.

from prettytable import PrettyTable
users = [
    {"id": 101, "name": "Carol", "role": "Admin"},
    {"id": 102, "name": "David", "role": "Editor"},
    {"id": 103, "name": "Susan", "role": "Viewer"}
]
# Create the table and get field names from the first dictionary's keys
table = PrettyTable()
table.field_names = users[0].keys()
for user in users:
    table.add_row(user.values())
print(table)

Output:

+-----+--------+---------+
| id  |  name  |   role  |
+-----+--------+---------+
| 101 |  Carol |  Admin  |
| 102 |  David |  Editor |
| 103 |  Susan |  Viewer |
+-----+--------+---------+

c. From a CSV File

You can use Python's built-in csv module to read a file and feed it to prettytable.

import csv
from prettytable import PrettyTable
# Assume 'data.csv' exists with the following content:
# Name,Department,Salary
# Alice,Engineering,90000
# Bob,Sales,75000
# Charlie,HR,65000
with open('data.csv', 'r') as f:
    reader = csv.reader(f)
    data = list(reader) # Convert CSV reader to a list of lists
table = PrettyTable()
table.add_rows(data)
# You might want to capitalize the field names
table.field_names = [name.capitalize() for name in table.field_names]
print(table)

Exporting the Table

You can export your table to various formats.

from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["X", "X^2", "X^3"]
for i in range(1, 6):
    table.add_row([i, i**2, i**3])
# Export to HTML
html_output = table.get_html_string()
print("--- HTML Output ---")
print(html_output)
# Export to LaTeX
latex_output = table.get_latex_string()
print("\n--- LaTeX Output ---")
print(latex_output)
# Export to a plain string without borders
plain_output = table.get_string(header=False, borders=False)
print("\n--- Plain String Output ---")
print(plain_output)

Summary of Key Attributes and Methods

Feature/Method Description
PrettyTable() Constructor for a new table.
table.field_names = [...] Sets the column headers.
table.add_row([...]) Adds a single row to the table.
table.add_rows([...]) Adds a list of rows to the table.
table.title = "..." Sets a title for the table.
table.align["ColName"] Sets alignment for a specific column (l, r, c).
table.max_width["ColName"] Sets the maximum character width for a column.
table.sortby = "ColName" Sorts the table by a specific column.
table.reversesort = True When used with sortby, reverses the sort order.
table.add_row_separator() Adds a horizontal line separator between rows.
table.get_string() Returns the table as a formatted string.
table.get_html_string() Returns the table as an HTML string.
table.get_latex_string() Returns the table as a LaTeX string.
分享:
扫描分享到社交APP
上一篇
下一篇