У сьогоднішній статті ми будемо говорити про бібліотеку prettytable, яка надає можливість створювати та виводити таблиці у консолі. Ми розглянемо цю бібліотеку та розберемо її основні функції.
Встановлення
Windows:
pip install prettytableMacOS:
pip3 install prettytableLinux:
pip install prettytableСтворення першої таблиці
творити таблицю за допомогою prettytable можна дуже легко. Таблицю можна створити трьома різними способами, які ми й розглянемо у днаій частині статті. Якраз додаємо внизу перший спосіб:
from prettytable import PrettyTable
console_table = PrettyTable()
console_table.field_names = ["Season", "Points", "Club", "City", "Games played", "Goals"]
console_table.add_row(["2024/25", 6, "Arsenal", "London", 2, 6])
console_table.add_row(["2024/25", 6, "Tottenham Hotspur", "London", 2, 5])
console_table.add_row(["2024/25", 6, "Liverpool", "Liverpool", 2, 7])
console_table.add_row(["2024/25", 4, "Chelsea", "London", 2, 5])
console_table.add_row(["2024/25", 4, "Nottingham Forest", "Nottingham", 2, 4])
print(console_table)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Тепер давайте розберемо, яким саме чином ми створили цю таблицю. Отже, спочатку ми імпортували саму бібліотеку prettytable:
from prettytable import PrettyTableДалі ми створили об’єкт console_table:
console_table = PrettyTable()Наступним кроком ми використали властивість field_names та задали назви наших колонок у таблиці як список зі значеннями:
console_table.field_names = ["Season", "Points", "Club", "City", "Games played", "Goals"]І на останок ми створили потрібну нам кількість рядків за допомогою функції add_row() та вказали список зі значеннями для кожної колонки:
console_table.add_row(["2024/25", 6, "Arsenal", "London", 2, 6])Звісно, у кінці ми вивели нашу таблицю у консоль:
print(console_table)Інші способи створення таблиці
Крім попереднього прикладу є й інші способи для створення таблиці у prettytable і у цій частині статті ми їх розглянемо.
У prettytable є також і функція add_rows(), яка дозволяє просто використати багатовимірний список для визначення значень у рядках. Ось приклад створення таблиці за допомогою цієї функції:
console_table.field_names = ["Season", "Points", "Club", "City", "Games played", "Goals"]
console_table.add_rows([
["2024/25", 6, "Arsenal", "London", 2, 6],
["2024/25", 6, "Tottenham Hotspur", "London", 2, 5],
["2024/25", 6, "Liverpool", "Liverpool", 2, 7],
["2024/25", 4, "Chelsea", "London", 2, 5],
["2024/25", 4, "Nottingham Forest", "Nottingham", 2, 4]
])
print(console_table)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Також дані для рядків можна вказувати через створення колонок за допомогою функції add_column(). Тобто у функції add_column() ми вказуємо одразу й назву колонки, й значення рядків для цієї колонки. Ось приклад створення таблиці таким чином:
console_table.add_column("Season", ["2024/25", "2024/25", "2024/25", "2024/25", "2024/25"])
console_table.add_column("Points", [6, 6, 6, 4, 4])
console_table.add_column("Club", ["Arsenal", "Tottenham Hotspur", "Liverpool", "Chelsea", "Nottingham Forest"])
console_table.add_column("City", ["London", "London", "Liverpool", "London", "Nottingham"])
console_table.add_column("Games played", [2, 2, 2, 2, 2])
console_table.add_column("Goals", [6, 5, 7, 5, 4])
print(console_table)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Ось таким чином різними способами можна створювати таблиці.
Секції таблиці
У prettytable можна ж також і додавати секції до таблиці. Тобто за допомогою цих секцій ми можемо розділити кожен рядок. Щоб додати секції до нашої таблиці нам треба використтати метод add_divider(), який і розділить таблицю на секції.
Ось приклад таблиці, розділеної на секції:
console_table.field_names = ["Season", "Points", "Club", "City", "Games played", "Goals"]
console_table.add_row(["2024/25", 6, "Arsenal", "London", 2, 6])
console_table.add_divider()
console_table.add_row(["2024/25", 6, "Tottenham Hotspur", "London", 2, 5])
console_table.add_divider()
console_table.add_row(["2024/25", 6, "Liverpool", "Liverpool", 2, 7])
console_table.add_divider()
console_table.add_row(["2024/25", 4, "Chelsea", "London", 2, 5])
console_table.add_divider()
console_table.add_row(["2024/25", 4, "Nottingham Forest", "Nottingham", 2, 4])
print(console_table)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Також можна скористатися параметром divider у методі add_row() та вказати його значення True. Таким чином отримаємо такий самий результат, що й попередній.
Ось приклад використання параметра divider:
console_table.field_names = ["Season", "Points", "Club", "City", "Games played", "Goals"]
console_table.add_row(["2024/25", 6, "Arsenal", "London", 2, 6], divider=True)
console_table.add_row(["2024/25", 6, "Tottenham Hotspur", "London", 2, 5], divider=True)
console_table.add_row(["2024/25", 6, "Liverpool", "Liverpool", 2, 7], divider=True)
console_table.add_row(["2024/25", 4, "Chelsea", "London", 2, 5], divider=True)
console_table.add_row(["2024/25", 4, "Nottingham Forest", "Nottingham", 2, 4], divider=True)
print(console_table)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Якщо для побудови таблиці ви користувалися методоми add_rows() або add_column(), то роздільники ви ніяк не зможете використати, адже їх немає для цих методів. Роздільники можна створити тільки якщо використовуєте метод add_row().
Прості стилі таблиці
У prettytable ми звісно можемо ще й задавати стиль таблиці. Для цбого треба імпортувати із бібліотеки prettytable клас TableStyle застосувати метод set_style() і вказати стиль після крапки.
Для початку оберемо стиль за замовчуванням — DEFAULT:
from prettytable import PrettyTable, TableStyle
console_table = PrettyTable()
console_table.set_style(TableStyle.DEFAULT)+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Стиль MARKDOWN:
console_table.set_style(TableStyle.MARKDOWN)| Season | Points | Club | City | Games played | Goals |
| :-----: | :----: | :---------------: | :--------: | :----------: | :---: |
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |Стиль PLAIN_COLUMNS:
console_table.set_style(TableStyle.PLAIN_COLUMNS)
Стиль MSWORD_FRIENDLY:
console_table.set_style(TableStyle.MSWORD_FRIENDLY)| Season | Points | Club | City | Games played | Goals |
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |Стиль ORGMODE:
console_table.set_style(TableStyle.ORGMODE)|---------+--------+-------------------+------------+--------------+-------|
| Season | Points | Club | City | Games played | Goals |
|---------+--------+-------------------+------------+--------------+-------|
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
|---------+--------+-------------------+------------+--------------+-------|Стиль SINGLE_BORDER:
console_table.set_style(TableStyle.SINGLE_BORDER)┌─────────┬────────┬───────────────────┬────────────┬──────────────┬───────┐
│ Season │ Points │ Club │ City │ Games played │ Goals │
├─────────┼────────┼───────────────────┼────────────┼──────────────┼───────┤
│ 2024/25 │ 6 │ Arsenal │ London │ 2 │ 6 │
│ 2024/25 │ 6 │ Tottenham Hotspur │ London │ 2 │ 5 │
│ 2024/25 │ 6 │ Liverpool │ Liverpool │ 2 │ 7 │
│ 2024/25 │ 4 │ Chelsea │ London │ 2 │ 5 │
│ 2024/25 │ 4 │ Nottingham Forest │ Nottingham │ 2 │ 4 │
└─────────┴────────┴───────────────────┴────────────┴──────────────┴───────┘Стиль DOUBLE_BORDER:
console_table.set_style(TableStyle.DOUBLE_BORDER)╔═════════╦════════╦═══════════════════╦════════════╦══════════════╦═══════╗
║ Season ║ Points ║ Club ║ City ║ Games played ║ Goals ║
╠═════════╬════════╬═══════════════════╬════════════╬══════════════╬═══════╣
║ 2024/25 ║ 6 ║ Arsenal ║ London ║ 2 ║ 6 ║
║ 2024/25 ║ 6 ║ Tottenham Hotspur ║ London ║ 2 ║ 5 ║
║ 2024/25 ║ 6 ║ Liverpool ║ Liverpool ║ 2 ║ 7 ║
║ 2024/25 ║ 4 ║ Chelsea ║ London ║ 2 ║ 5 ║
║ 2024/25 ║ 4 ║ Nottingham Forest ║ Nottingham ║ 2 ║ 4 ║
╚═════════╩════════╩═══════════════════╩════════════╩══════════════╩═══════╝Ось такі стилі ми можемо обрати.
Просунуті стилі таблиць
Ми вже розглянули базові стилі таблиць, а тепер поринемо у більш поросунутий, так би мовити, рівень стилів у prettytable. Тепер ми зможемо створювати кастомні стилі за допомогою наданих нам властивостей. А зараз ми розглянемо кожну із них.
Властивість border додає рамку до таблиці:
console_table.border = True+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+console_table.border = FalseSeason Points Club City Games played Goals
2024/25 6 Arsenal London 2 6
2024/25 6 Tottenham Hotspur London 2 5
2024/25 6 Liverpool Liverpool 2 7
2024/25 4 Chelsea London 2 5
2024/25 4 Nottingham Forest Nottingham 2 4Властивість preserve_internal_border:
console_table.border = False
console_table.preserve_internal_border = TrueSeason | Points | Club | City | Games played | Goals
---------+--------+-------------------+------------+--------------+-------
2024/25 | 6 | Arsenal | London | 2 | 6
2024/25 | 6 | Tottenham Hotspur | London | 2 | 5
2024/25 | 6 | Liverpool | Liverpool | 2 | 7
2024/25 | 4 | Chelsea | London | 2 | 5
2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4console_table.border = False
console_table.preserve_internal_border = False Season Points Club City Games played Goals
2024/25 6 Arsenal London 2 6
2024/25 6 Tottenham Hotspur London 2 5
2024/25 6 Liverpool Liverpool 2 7
2024/25 4 Chelsea London 2 5
2024/25 4 Nottingham Forest Nottingham 2 4 Властивість header:
console_table.header = True+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+console_table.header = False+---------+---+-------------------+------------+---+---+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+---+-------------------+------------+---+---+Властивість hrules приймає клас HRuleStyle, який має атрибути FRAME, HEADER, ALL, NONE. Проте, цей клас треба імпортувати. Ось приклад цієї властивості:
from prettytable import PrettyTable
from prettytable.prettytable import HRuleStyle
console_table = PrettyTable()
console_table.hrules = HRuleStyle.FRAME+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+console_table.hrules = HRuleStyle.HEADER| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |console_table.hrules = HRuleStyle.ALL+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+console_table.hrules = HRuleStyle.NONE| Season | Points | Club | City | Games played | Goals |
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |Виведення таблиці
До цього ми використовували звичайний print() для виведення таблиці у консоль, але у prettytable для цього є окрема функція — get_string(). Завдяки функції get_string() ми можемо виводити окремі частини таблиці, сортувати дані таблиці, змінювати форматування таблиці та фільтрувати таблицю.
Розглянемо усі ці можливості по черзі, а конкретно почнемо із виведення різних частин таблиці. Для цього нам потрібно вказати у методі get_string() параметр fields, куди ми передаємо колонки, які хочемо вивести.
Ось приклад виведення тільки чотирьох колонок з таблиці:
print(console_table.get_string(fields=["Season", "Points", "Club", "City"]))+---------+--------+-------------------+------------+
| Season | Points | Club | City |
+---------+--------+-------------------+------------+
| 2024/25 | 6 | Arsenal | London |
| 2024/25 | 6 | Tottenham Hotspur | London |
| 2024/25 | 6 | Liverpool | Liverpool |
| 2024/25 | 4 | Chelsea | London |
| 2024/25 | 4 | Nottingham Forest | Nottingham |
+---------+--------+-------------------+------------+Також у метода get_string() є параметри start та end. У параметрі start вказуємо індекс рядка, з якого ми починаємо виведення, а у end рядка, яким ми закінчуємо нашу таблицю.
Ось приклад виведення частини таблиці з цими параметрами:
print(console_table.get_string(start=0, end=3))+---------+--------+-------------------+-----------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+-----------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
+---------+--------+-------------------+-----------+--------------+-------+Тепер розглянемо як сортувати таблицю за якоюсь конкретною колонкою. Це можна зробити за домопогою параметра sortby, якому вказуємо колонку, за якою хочемо сортувати таблицю.
Ось приклад сортування таблиці за колонкою Goals:
print(console_table.get_string(sortby="Goals"))+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
+---------+--------+-------------------+------------+--------------+-------+Як бачимо, таблиця розсортована за принципом від найменшого до найбільшого. Якщо ми захочемо зробити так, щоб найбільші значення були вище, а найменші нижче, то треба використати параметр reversesort. Вказуємо reversesort значення True і запускаємо код:
print(console_table.get_string(sortby="Goals", reversesort=True))+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Отримали потрібний нам принцип сортування.
Положення тексту у таблиці
За замовчуванням текст у колонках розташовується посередині, але ми можемо змінювати розташування тексту за допомогою властивості align.
Отже, одразу наводимо приклади, а конкретно задамо розташування по правій стороні:
console_table.align = "r"
print(console_table.get_string())+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+По лівій стороні:
console_table.align = "l"
print(console_table.get_string())+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+По центру:
console_table.align = "c"
print(console_table.get_string())+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Також ми можемо обирати конкретну колонку, до якої хочемо застосувати конккретне розташування. Просто вказуємо біля властивості align колонку у квадкатних дужках.
Ось приклад:
console_table.align["Season"] = "l"
console_table.align["Points"] = "l"
console_table.align["Club"] = "c"
console_table.align["City"] = "c"
console_table.align["Games played"] = "c"
console_table.align["Goals"] = "c"
print(console_table.get_string())+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+Ось таку таблицю ми отримали.
Формат виведення таблиць
У цій частині статті ми будемо виводити таблицю у різних доступних у бібліотеці форматах. У prettytable є метод get_formatted_string(), який має параметр out_format, що приймає різні формати виведення таблиці. За замовчуванням параметр out_format має значення
Отже, спочатку приклад з out_format=”text”:
print(console_table.get_formatted_string(out_format="text"))+---------+--------+-------------------+------------+--------------+-------+
| Season | Points | Club | City | Games played | Goals |
+---------+--------+-------------------+------------+--------------+-------+
| 2024/25 | 6 | Arsenal | London | 2 | 6 |
| 2024/25 | 6 | Tottenham Hotspur | London | 2 | 5 |
| 2024/25 | 6 | Liverpool | Liverpool | 2 | 7 |
| 2024/25 | 4 | Chelsea | London | 2 | 5 |
| 2024/25 | 4 | Nottingham Forest | Nottingham | 2 | 4 |
+---------+--------+-------------------+------------+--------------+-------+HTML формат:
print(console_table.get_formatted_string(out_format="html"))<table>
<thead>
<tr>
<th>Season</th>
<th>Points</th>
<th>Club</th>
<th>City</th>
<th>Games played</th>
<th>Goals</th>
</tr>
</thead>
<tbody>
<tr>
<td>2024/25</td>
<td>6</td>
<td>Arsenal</td>
<td>London</td>
<td>2</td>
<td>6</td>
</tr>
<tr>
<td>2024/25</td>
<td>6</td>
<td>Tottenham Hotspur</td>
<td>London</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>2024/25</td>
<td>6</td>
<td>Liverpool</td>
<td>Liverpool</td>
<td>2</td>
<td>7</td>
</tr>
<tr>
<td>2024/25</td>
<td>4</td>
<td>Chelsea</td>
<td>London</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>2024/25</td>
<td>4</td>
<td>Nottingham Forest</td>
<td>Nottingham</td>
<td>2</td>
<td>4</td>
</tr>
</tbody>
</table>JSON формат:
print(console_table.get_formatted_string(out_format="json"))[
[
"Season",
"Points",
"Club",
"City",
"Games played",
"Goals"
],
{
"City": "London",
"Club": "Arsenal",
"Games played": 2,
"Goals": 6,
"Points": 6,
"Season": "2024/25"
},
{
"City": "London",
"Club": "Tottenham Hotspur",
"Games played": 2,
"Goals": 5,
"Points": 6,
"Season": "2024/25"
},
{
"City": "Liverpool",
"Club": "Liverpool",
"Games played": 2,
"Goals": 7,
"Points": 6,
"Season": "2024/25"
},
{
"City": "London",
"Club": "Chelsea",
"Games played": 2,
"Goals": 5,
"Points": 4,
"Season": "2024/25"
},
{
"City": "Nottingham",
"Club": "Nottingham Forest",
"Games played": 2,
"Goals": 4,
"Points": 4,
"Season": "2024/25"
}
]CSV формат:
print(console_table.get_formatted_string(out_format="csv"))Season,Points,Club,City,Games played,Goals
2024/25,6,Arsenal,London,2,6
2024/25,6,Tottenham Hotspur,London,2,5
2024/25,6,Liverpool,Liverpool,2,7
2024/25,4,Chelsea,London,2,5
2024/25,4,Nottingham Forest,Nottingham,2,4LATEX формат:
print(console_table.get_formatted_string(out_format="latex"))\begin{tabular}{cccccc}
Season & Points & Club & City & Games played & Goals \\
2024/25 & 6 & Arsenal & London & 2 & 6 \\
2024/25 & 6 & Tottenham Hotspur & London & 2 & 5 \\
2024/25 & 6 & Liverpool & Liverpool & 2 & 7 \\
2024/25 & 4 & Chelsea & London & 2 & 5 \\
2024/25 & 4 & Nottingham Forest & Nottingham & 2 & 4 \\
\end{tabular}MediaWiki формат:
print(console_table.get_formatted_string(out_format="mediawiki")){| class="wikitable"
|-
! Season !! Points !! Club !! City !! Games played !! Goals
|-
| 2024/25 || 6 || Arsenal || London || 2 || 6
|-
| 2024/25 || 6 || Tottenham Hotspur || London || 2 || 5
|-
| 2024/25 || 6 || Liverpool || Liverpool || 2 || 7
|-
| 2024/25 || 4 || Chelsea || London || 2 || 5
|-
| 2024/25 || 4 || Nottingham Forest || Nottingham || 2 || 4
|}Також, крім параметра out_format, можна ще й використовувати окремі методи форматування для досягнення таких же результатів. Ось наведений приклад таких методів, вони будуть давати той самий результат, що й get_formatted_string() із параметром out_format:
print(console_table.get_string())
print(console_table.get_html_string())
print(console_table.get_json_string())
print(console_table.get_csv_string())
print(console_table.get_latex_string())
print(console_table.get_mediawiki_string())Ви можете або використовувати get_formatted_srting() із вказаним параметром або один із цих методів форматування. Все на ваш розсуд.
Висновок
Насправді цю статтю я готував вже давно, але не міг виипустити через деякі причини. На даний момент — це найдовша моя стаття і, якщо чесно, хотілося б мені побільше таких. Отже, сподіваюся, що вам було цікаво це читати і ви й справді дізналися для себе щось нове. У цьому матеріалі ми пройшли доволі багато аспектів бібліотеки prettytable: від створення базової таблиці до ріхних налаштувань її стилів та фільтрування. Усім дякую за увагу!