Pretty tables python установка

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Format tabular data with pretty styles.

License

Licenses found

Kyostenas/prettyTables

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Pretty Tables

This is a python package that aims to provide a simple and pretty way of printing tables to the console making use of a class.

The idea started as an attempt to reproduce the behavior of the PM2 package when it displays tables to show data. Later, heavy inspiration came of two other python packages:

  • Jazzband’sprettytable (The names are similar by accident). Uses a class too.
  • Astanin’stabulate. A very simple to use and efficient package.

A big part of the behavior of this package was replicated from these.

pip install prettyTables on Windows.

pip3 install prettyTables on Linux

Creating a table is simple.

from prettyTables import Table new_table = Table() print(new_table) 

This is an empty table. It has no data so it only displays this strange thing.

It’s possible to add data as columns or rows, or even alternating each one. Any untitled column will be named automatically.

new_table.add_column('Name', ['Jade', 'John', 'Jane']) new_table.add_column('Age', [20, 30, 40]) new_table.add_column('Results', [9.651, 3, 245.7]) print(new_table) 
+----------------------+ | Name Age Results | +======+=====+=========+ | Jade | 20 | 9.651 | | John | 30 | 3 | | Jane | 40 | 245.7 | +------+-----+---------+ 
new_table = Table() new_table.add_column('Name', ['Jade', 'John', 'Jane']) new_table.add_column('Age', [20, 30, 40]) new_table.add_column('Test\nResults', [9.651, 3, 245.7]) new_table.add_row(['Piotr\nBaltimore', 27, 3.5]) new_table.add_row(['Sam', 21, 0.6519]) print(new_table) 
+----------------------------+ | Name Age Test | | Results | +===========+=====+==========+ | Jade | 20 | 9.651 | | John | 30 | 3 | | Jane | 40 | 245.7 | | Piotr | 27 | 3.5 | | Baltimore | | | | Sam | 21 | 0.6519 | +-----------+-----+----------+ 

As it is visible, the table will format automatically new lines and data types, for now without trying to parse strings that could be converted to another type.

The Table class offers a variety of options that allow things like showing the index of each row, changing the style of the table, hiding the headers, etc.

new_table = Table() new_table.add_column('Name', ['Jade', 'John']) new_table.add_column('Age', [20, 30]) new_table.add_column('Test\nResults', [9.651, 3, 245.7]) new_table.add_row(['Piotr\nBaltimore', 27, 3.5]) new_table.add_row(['Sam', 21]) new_table.show_index = True new_table.style_name = 'pretty_columns' new_table.missing_value = '?' print(new_table) 
╒═══╤═══════════╤═════╤═════════╕ │ i │ Name │ Age │ Test │ │ │ │ │ Results │ ╞═══╪═══════════╪═════╪═════════╡ │ 0 │ Jade │ 20 │ 9.651 │ │ 1 │ John │ 30 │ 3 │ │ 2 │ ? │ ? │ 245.7 │ │ 3 │ Piotr │ 27 │ 3.5 │ │ │ Baltimore │ │ │ │ 4 │ Sam │ 21 │ ? │ ╘═══╧═══════════╧═════╧═════════╛ 

The missing value aligns as if it was of the same type of the other data in the column.

This shows how to get the row and column count. If the index is shown, this count remains unaffected by that column, although, you can get the internal count.

new_table.show_index = False new_table.show_headers = False print(new_table) print('row:', new_table.row_count) print('columns:', new_table.column_count) new_table.show_index = True print(new_table) print('internal_row_count:', new_table.internal_row_count) print('internal_column_count:', new_table.internal_column_count) 
╒═══════════╤════╤═════════╕ │ Jade │ 20 │ 9.651 │ │ John │ 30 │ 3 │ │ ? │ ? │ 245.7 │ │ Piotr │ 27 │ 3.5 │ │ Baltimore │ │ │ │ Sam │ 21 │ ? │ ╘═══════════╧════╧═════════╛ row: 5 columns: 3 ╒═══╤═══════════╤════╤═════════╕ │ 0 │ Jade │ 20 │ 9.651 │ │ 1 │ John │ 30 │ 3 │ │ 2 │ ? │ ? │ 245.7 │ │ 3 │ Piotr │ 27 │ 3.5 │ │ │ Baltimore │ │ │ │ 4 │ Sam │ 21 │ ? │ ╘═══╧═══════════╧════╧═════════╛ internal_row_count: 5 internal_column_count: 4 
  • Alignment only works when sending data as its type. Type parsing is still missing.
  • When auto-wrapping is False the adjusting of the table to the console will potentially fail.
  • Naming a column «i» will mess up what columns show if the index column is displaying.
  • Exponential numbers only align incorrectly.

About

Format tabular data with pretty styles.

Источник

PrettyTable — вывод табличных данных в ASCII

PrettyTable - вывод табличных данных в ASCII

PrettyTable — это библиотека Python, разработанная для простого и быстрого отображения табличных данных в визуально удобных таблицах ASCII.

Введение

По словам автора библиотеки он был очень вдохновлен таблицами ASCII, используемых в оболочке PostgreSQL. PrettyTable позволяет выбирать, какие столбцы должны быть напечатаны, производить независимое выравнивание столбцов, а так же печать частично таблицы путем указания диапазона строк.

Установка

Существует возможность установить стабильную версию или же экспериментальную, на ваш выбор, воспользуемся для этого пакетным менеджером

Стабильная версия

Воспользуемся пакетным менеджером pip для установки из репозитория

pip install -U prettytable

Эксперементальная версия

Метод установки схожий со стабильной версией, но теперь мы устанавливаем ее из репозитория автора на github.

pip install -U git+https://github.com/jazzband/prettytable

Использование

Создадим объект prettytable или другими словами пустую таблицу.

from prettytable import PrettyTable x = PrettyTable()

Для того чтобы поместить в него наши данные, у нас есть несколько способов это выполнить.

Построчный ввод

Вы можете добавлять данные по одной строке за раз. Для этого можно сначала задать имена полей с помощью атрибута field_names, а затем добавить строки по одной с помощью метода add_row:

x.field_names = ["Сотрудник", "Возраст", "Должность", "Оклад"] x.add_row(["Николай", 43, "Плотник", 25000]) x.add_row(["Андрей", 29, "Менеджер", 30000]) x.add_row(["Анатолий", 19, "Практикант", 12500]) x.add_row(["Юлия", 27, "Секретарь", 35000]) x.add_row(["Наталья", 35, "Руководитель отдела продаж", 40000]) x.add_row(["Екатерина", 30, "Менеджер", 27000]) x.add_row(["Георгий", 44, "Охранник", 17500])

Ввод данных по одному столбцу

Вы также можете добавлять данные по одному столбцу за раз. Для этого используется метод add_column, который принимает два аргумента, название столбца и список или кортеж, содержащий значения.

x.add_column("Сотрудник", ["Николай", "Андрей", "Анатолий", "Юлия", "Наталья", "Екатерина", "Георгий"]) x.add_column("Возраст", [43, 29, 19, 27, 35, 30, 44]) x.add_column("Должность", ["Плотник", "Менеджер", "Практикант", "Секретарь", "Руководитель отдела продаж", "Менеджер", "Охранник"]) x.add_column("Annual Оклад", [25000, 30000, 12500, 35000, 40000, 27000, 17500])

Импорт данных из CSV-файла

Если вы храните данные в таблицах CSV вы можете прочитать эти данные в красивую таблицу всего парой строк кода:

from prettytable import from_csv f = open("table.csv", "r") table = from_csv(f) f.close()

Импорт из базы данных

Если вы храните информацию в реляционных базах данных, то при наличии поддержки Python DB-API в реализации ее библиотеке вы сможете импортировать их в таблицу с помощью объекта курсора

import sqlite3 from prettytable import from_cursor conn = sqlite3.connect("db.sqlite3") cur = conn.cursor() cur.execute("SELECT field FROM table WHERE = from_cursor(cur)

Удаление данных

Существует три способа удаления данных

  • Метод del_row принимает целочисленный индекс одной строки для удаления.
  • Метод clear_rows не принимает аргументов и удаляет все строки в таблице, но сохраняет имена полей такими, какими они были, чтобы вы могли повторно заполнить их данными.
  • Метод clear не принимает аргументов и удаляет все строки и все имена полей. Это не совсем то же самое, что создание нового экземпляра таблицы, хотя связанные со стилем настройки сохраняются.

Отображение вашей таблицы в ASCII

Основная цель PrettyTable — позволить вам печатать таблицы в привлекательной форме ASCII, например так:

+-----------+---------+----------------------------+-------+ | Сотрудник | Возраст | Должность | Оклад | +-----------+---------+----------------------------+-------+ | Николай | 43 | Плотник | 25000 | | Андрей | 29 | Менеджер | 30000 | | Анатолий | 19 | Практикант | 12500 | | Юлия | 27 | Секретарь | 35000 | | Наталья | 35 | Руководитель отдела продаж | 40000 | | Екатерина | 30 | Менеджер | 27000 | | Георгий | 44 | Охранник | 17500 | +-----------+---------+----------------------------+-------+

Распечатать таблицу в формате ASCII очень просто, достаточно сделать это:

Заключение

Мы рассмотрели библиотеку PrettyTable, варианты ее установки, принципы использования, построчный ввод, импорт данных из csv таблицы и базы данных.

Это не полный функционал, более подробную информацию об использование параметров таблицы, сортировки данных, печать в другие форматы (HTML/JSON) вы можете найти на официальной странице разработчика

Программирую на Python с 2017 года. Люблю создавать контент, который помогает людям понять сложные вещи. Не представляю жизнь без непрерывного цикла обучения, спорта и чувства юмора.

Ссылка на мой github есть в шапке. Залетай.

Источник

Читайте также:  Python dictionary добавить пару
Оцените статью