Coder Social home page Coder Social logo

beautifultable's Introduction

beautifultable

https://api.codacy.com/project/badge/Grade/7a76eb35ad4e450eaf00339e98381511 https://github.com/pri22296/beautifultable/actions/workflows/build.yml/badge.svg?branch=master Documentation Status

Introduction

This Package provides BeautifulTable class for easily printing tabular data in a visually appealing format to a terminal.

Features included but not limited to:

  • Full customization of the look and feel of the table
  • Build the Table as you wish, By adding rows, or by columns or even mixing both these approaches.
  • Full support for colors using ANSI sequences or any library of your choice. It just works.
  • Plenty of predefined styles for multiple use cases and option to create custom ones.
  • Support for Unicode characters.
  • Supports streaming table when data is slow to retrieve.

Links

Usage

Here is an example of how you can use beautifultable:

>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.rows.append(["Jacob", 1, "boy"])
>>> table.rows.append(["Isabella", 1, "girl"])
>>> table.rows.append(["Ethan", 2, "boy"])
>>> table.rows.append(["Sophia", 2, "girl"])
>>> table.rows.append(["Michael", 3, "boy"])
>>> table.rows.header = ["S1", "S2", "S3", "S4", "S5"]
>>> table.columns.header = ["name", "rank", "gender"]
>>> print(table)
+----+----------+------+--------+
|    |   name   | rank | gender |
+----+----------+------+--------+
| S1 |  Jacob   |  1   |  boy   |
+----+----------+------+--------+
| S2 | Isabella |  1   |  girl  |
+----+----------+------+--------+
| S3 |  Ethan   |  2   |  boy   |
+----+----------+------+--------+
| S4 |  Sophia  |  2   |  girl  |
+----+----------+------+--------+
| S5 | Michael  |  3   |  boy   |
+----+----------+------+--------+

You can learn more about beautifultable at this Tutorial

Installation

python3 -m pip install beautifultable

Changelog

Development

v1.1.0

  • Drop support for Python 3.4, 3.5 and 3.6
  • Add official support for python 3.9 and 3.10
  • Added asdict and aslist method on the row object. (Thanks to @Agent-Hellboy)
  • Added from_csv and to_csv methods to export/import a csv file. (Thanks to @Agent-Hellboy)
  • Added from_df and to_df methods to export/import a dataframe. (Thanks to @Agent-Hellboy)

v1.0.1

  • Fixed an issue where appending a column with a header to an empty table left the table instance in an inconsistent state.

v1.0.0

  • Added two new views rows and columns to the BeautifulTable class. Most of the existing methods have been deprecated. Methods of the form {}_row and {}_column have been moved to views rows.{} and columns.{}``(ex. ``append_row is now rows.append). Calling older deprecated methods will now raise a FutureWarning. Special methods such as __len__, __iter__, etc. have also been moved to the respective views. For details, refer the API documentation and the Updated Tutorial
  • The existing styling attributes have also been deprecated. A new border property can be accessed to control all styling attributes affecting the border. Rest of the attributes can be accessed from it's respective view.
  • Added support for row headers. As a result rows can now be accessed by their keys similar to columns
  • Added two new methods to_csv and from_csv to directly export/import to a csv file. (Thanks to @dinko-pehar)
  • Added BeautifulTable.rows.filter method to generate a new table with only certain rows
  • Added a new shape attribute to the BeautifulTable class which returns a tuple of form (nrow, ncol)
  • Added new attribute BeautifulTable.columns.header.alignment which can be used to have a seperate header alignment. The default behaviour is to inherit BeautifulTable.columns.alignment
  • Updated BeautifulTable.rows.sort (earlier BeautifulTable.sort) method to now also accept any callables as a key.
  • Updated behaviour of BeautifulTable.columns.width (earlier BeautifulTable.column_widths). It no longer overrides user specified widths by default. You can reset it to default by setting it to "auto"
  • Deprecated attribute serialno and serialno_header. User can now easily implement this functionality by using row headers if required
  • Deprecated methods get_table_width(), copy() and get_string().
  • Deprecated constructor arguments and class attributes named sign_mode, numeric_precision, max_width and renamed to sign, precision and maxwidth respectively
  • Fixed an issue where table was malformed if blessings module was used to generate colored strings.
  • Fixed issues with the existing implementation of __iter__, __copy__ and __deepcopy__ which should now work more reliably.
  • Fixed an issue where default padding could not be set to 0. (Thanks to @furlongm)
  • Fixed several memory leak issues by ensuring that all internal objects hold only a weak reference to the table instance.
  • Dropped support for Python 2

v0.8.0

  • Dropped support for Python 3.3
  • Added support for streaming tables using a generator for cases where data retrieval is slow
  • Alignment, padding, width can now be set for all columns using a simplified syntax like table.column_alignments = beautifultable.ALIGN_LEFT

v0.7.0

  • Added 4 new styles, STYLE_BOX, STYLE_BOX_DOUBLED, STYLE_BOX_ROUNDED, STYLE_GRID.
  • Renamed STYLE_RESTRUCTURED_TEXT to STYLE_RST
  • wcwidth is now an optional dependency
  • Updated the algorithm for calculating width of columns(better division of space among columns)
  • Added support for Paragraphs(using \n character)
  • Added finer control for intersection characters using 12 new attributes intersect_{top|header|row|bottom}_{left|mid|right}
  • Added the ability to also accept bytestrings instead of unicode
  • Deprecated attribute intersection_char
  • Deprecated methods get_top_border(), get_bottom_border(), get_header_separator(), get_row_separator(), auto_calculate_width()
  • Fixed an issue with WEP_ELLIPSIS and WEP_STRIP when using multibyte characters
  • Fixed an issue where table would not be in proper form if column_width is too low

v0.6.0

  • Added support for handling Multi byte strings
  • Added support for colored strings using ANSI escape sequences
  • Added constraint where all strings must be unicode
  • Fixed an issue where sometimes width was calculated as higher than intended

v0.5.3

  • Added support for handing color codes using ANSI escape sequences(experimental)
  • Fixed collections ABCs deprecation warning

v0.5.2

  • Added new style STYLE_NONE
  • Fixed issue regarding improper conversion of non-string floats

v0.5.1

  • Added detect_numerics boolean for toggling automatic numeric conversion

v0.5.0

  • Added new property serialno_header
  • Deprecated methods with misspelled "seperator" in their name.
  • Fixed an issue where table was corrupted when column_count was too high

v0.4.0

  • Added predefined styles for easier customization
  • Added reverse argument to sort() method
  • Fixed enum34 dependency for python versions prior to 3.4

v0.3.0

  • Added property serialno for auto printing serial number
  • Fixed an issue with sign_mode related to str conversion
  • Fixed bugs related to python version prior to 3.3
  • Fixed exception on WEP_ELLIPSIS and token length less than 3
  • Fixed printing issues with empty table

v0.2.0

  • Added python 2 support

v0.1.3

  • Fixed minor issues

v0.1.2

  • Added new property default_padding
  • Added new method update_row
  • Fixed an issue in auto_calculate_width()

v0.1.1

  • Initial release on PyPI

Contribute

If you have any suggestions or bug reports, Please create a Issue. Pull Requests are always welcome.

License

This project is licensed under the MIT License - see the LICENSE.txt file for details.

Donation

Love beautifultable? Consider supporting the development :)

https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif

beautifultable's People

Contributors

agent-hellboy avatar cp-bagerard avatar digitronik avatar dinkopehar avatar furlongm avatar jayvdb avatar onmeac avatar pri22296 avatar sideboard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

beautifultable's Issues

typo in separator fields

All separator fields are spelled as seperator. It's not a major issue but needs fixing. It is desirable that the fix is backcompatible.

Print to string

Print prints to terminal. I would need something that can put the output in a string instead.

Inconsistent behavior on printing

>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.append_row([1])
>>> table.pop_row()
>>> print(table)
+--+
|  |
+--+
+--+
>>> table.append_row([1])
>>> table.pop_column()
>>> print(table)
+
||
+
+

How can I append the column?

Hello! As I understand I can't update the column with iterator with len more than it is now in column.

And on table like this update by key is not work.

>>> print(table)
+------+
| year |
+------+
| 2013 |
+------+
| 2014 |
+------+
| 2015 |
+------+
| 2016 |
+------+
| 2017 |
+------+
| 2012 |
+------+
| 2011 |
>>> l_now = list(table['year'])
>>> l_now.extend(['2010', '2009, 2018'])
>>> table['year'] = l_now
>>> print(table)
'Here is the same table'

As I understand I must pop and after create new column?

Version 0.7 BT: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-138: ordinal not in range(128)

I encountered this error using beautifultable v0.70 in python2.7.

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-138: ordinal not in range(128)

It occurred during

print(table)

when I used:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

or

from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

It printed nothing but noisy results:
╭─────────────────â”

problem in adding coloration to the table elements

I tried to use the library colored to add colors to table elements, but when printing, the formatting was rendered to plain text. I just now saw that Style_NONE was applied. Is the problem due to this command? how can i turn it to manual?

String improperly being converted to float

I have an element I'm trying to add to my table and it's the string "2e77754" which is an ID number for something. This gets improperly recognized as a float with value 2x10^77754 and thus returns "inf" in my table instead of the string "2e77754".

I think the issue is in /beautifultable/utils/convert_to_numeric.py

ResourseWarning and UserWarning cant be ingnored.

Hi,
First of all this is a great tool that im planning on using in my own project as a replacement for pandas dataframe. I love that you can index the elements inside a table unlike many other table packages.

However, everytime I print the a table to the console inside my own project I get the following warnings:
UserWarning: nperseg = 256 is greater than input length = 10, using nperseg = 10 .format(nperseg, input_length))
sys:1: ResourceWarning: unclosed file <_io.TextIOWrapper name=1 mode='w' encoding='utf8'>

The first warning is a result of my own builtin function and I have successfully filtered out that warning but it always pops back up whenever I use your tool to print a table to the console. Warning number two only appears if I use your tool. I tried suppressing the warning by doing:
simplefilter('ignore', UserWarning)
simplefilter('ignore', ResourceWarning)

but it just wont go away. DO you have any suggestions on how to deal with this issue?

breaking on python 2;

This seems to be breaking on python 2.

>>> import beautifultable
>>> t = beautifultable.BeautifulTable()
>>> t.column_headers = ["a", "b", "c"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/russ/.pyenv/versions/2.7.10/lib/python2.7/site-packages/beautifultable/beautifultable.py", line 231, in __setattr__
    super(BeautifulTable, self).__setattr__(name, value)
  File "/Users/russ/.pyenv/versions/2.7.10/lib/python2.7/site-packages/beautifultable/beautifultable.py", line 366, in column_headers
    raise TypeError("Headers should be of type 'str', not {}".format(type(i)))
TypeError: Headers should be of type 'str', not <type 'str'>

Misaligned when using colored strings via module Blessings

The printed table is misaligned when using colored data via module Blessings.
Here is an example.

from beautifultable import BeautifulTable
import blessings

term = blessings.Terminal()

table = BeautifulTable(max_width=120)

table.column_headers = [term.green('Header A'), term.cyan('Header B')]
table.append_row([term.yellow('data'), term.cyan('data')])

print(table)

Tested on:

  • Python 3.6.7 (default, Oct 22 2018, 11:32:17)

Screenshot of output:
image

Order of sorting

Hello! Don't find the sorting order of table. For example ascending or descending ordering. Is this method in your lib?

Different behaviour on Python 2 and 3

Python 3

+-------+----+-----+
| name  | ra | gen |
|       | nk | der |
+-------+----+-----+
| Jacob | 1  | boy |
+-------+----+-----+
| Isabe | 1  | gir |
|  lla  |    |  l  |
+-------+----+-----+
| Ethan | 2  | boy |
+-------+----+-----+
| Sophi | 2  | gir |
|   a   |    |  l  |
+-------+----+-----+
| Micha | 3  | boy |
|  el   |    |     |
+-------+----+-----+

Python 2

+------+----+-----+
| name | ra | gen |
|      | nk | der |
+------+----+-----+
| Jaco | 1  | boy |
|  b   |    |     |
+------+----+-----+
| Isab | 1  | gir |
| ella |    |  l  |
+------+----+-----+
| Etha | 2  | boy |
|  n   |    |     |
+------+----+-----+
| Soph | 2  | gir |
|  ia  |    |  l  |
+------+----+-----+
| Mich | 3  | boy |
| ael  |    |     |
+------+----+-----+

Print statement resets column widths

Whenever I use column_widths to change this parameter for a column and then run print(table), it resets the column's width back to the previous value.
So I have to use print(table.get_string(recalculate_width=False)) instead of the simple print statement.

Incorrect calculation of column width

Minimal example:

table = beautifultable.BeautifulTable(max_width=150)
table.column_headers = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
table.append_row(['q123456789012345678', 'a', 'b', 'c', 'd', 'e', 'f'])
print(table)

Output:

+----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+
|                                                             t                                                              | u | v | w | x | y | z |
+----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+
|                                                    q123456789012345678                                                     | a | b | c | d | e | f |
+----------------------------------------------------------------------------------------------------------------------------+---+---+---+---+---+---+

The first column is too wide. If I omit the last character, it works as expected:

table.append_row(['q12345678901234567', 'a', 'b', 'c', 'd', 'e', 'f'])
+--------------------+---+---+---+---+---+---+
|         t          | u | v | w | x | y | z |
+--------------------+---+---+---+---+---+---+
| q12345678901234567 | a | b | c | d | e | f |
+--------------------+---+---+---+---+---+---+

It also seems to work as expected if I change the max_width, or if I use fewer columns.

Malformed table when using WEP_STRIP or WEP_ELLIPSIS with multibyte characters

When using WEP_ELLIPSIS or WEP_STRIP table is malformed when using east asian characters as shown below.

|              name              | rank | gender |
+--------------------------------+------+--------+
| こんにちはこんにちはこんにちはこんにちはこんにちはこん... |  1   |  boy   |
+--------------------------------+------+--------+
|            Isabella            |  1   |  girl  |
+--------------------------------+------+--------+
|             Ethan              |  2   |  boy   |
+--------------------------------+------+--------+
|             Sophia             |  2   |  girl  |
+--------------------------------+------+--------+
|            Michael             |  3   |  boy   |
+--------------------------------+------+--------+

Support for subtables

In e4d41c2 , ability to handle newline character was added. Hence with proper max_widths, another table could be in a cell of parent table. Logic could be added to adjust the max_width to ensure internal tables are not wrapped or stripped.

Improper table if column_width is calculated to be too low

Test case

table = BeautifulTable(max_width=30)
table.column_headers = ["name", "rank", "gender"]
table.append_row(["Sophia", 2, "girl"*20])
table.append_row(["Michael", 3, "boy"])
print(table)

Output

|  | rank |      gender      |
| n |      |                  |
| a |      |                  |
| m |      |                  |
| e |      |                  |
+--+------+------------------+
|  |  2   | girlgirlgirlgirl |
| S |      | girlgirlgirlgirl |
| o |      | girlgirlgirlgirl |
| p |      | girlgirlgirlgirl |
| h |      | girlgirlgirlgirl |
| i |      |                  |
| a |      |                  |
+--+------+------------------+
|  |  3   |       boy        |
| M |      |                  |
| i |      |                  |
| c |      |                  |
| h |      |                  |
| a |      |                  |
| e |      |                  |
| l |      |                  |
+--+------+------------------+```

beautifultable is not beautiful for multibyte string

Hi,
I'm trying to print multibyte string in beautifultable. But the result is not beautiful, unsuitable number of space.

like this:

from beautifultable import BeautifulTable
table = BeautifulTable()
table.column_headers = ['Language', 'Hello']
table.append_row(['Japanese', 'こんにちは'])
table.append_row(['English', 'Hello'])
table.append_row(['Chinese', '你好'])
table.append_row(['Emoji', '😉'])
print(table)
+----------+-------+
| Language | Hello |
+----------+-------+
| Japanese | こんにちは |
+----------+-------+
| English  | Hello |
+----------+-------+
| Chinese  |  你好   |
+----------+-------+
|  Emoji   |   😉   |
+----------+-------+

Is there any way to solve this problem?
Thanks.

$ pip freeze | grep beautifultable
beautifultable==0.5.3

Float print formatting broken?

This seemed off to me:

python -c "import beautifultable; t = beautifultable.BeautifulTable(); t.append_row(['3.14']); print('%s' % t)"

I get:
+--------------------+
| 3.1400000000000001 |
+--------------------+

when I expect:

+------+
| 3.14 |
+------+

Since I actually specified the row as a string I'm surprised to see was treated as a float (float gives same behavior).

Handle newlines

Test Case

from beautifultable import BeautifulTable

x = BeautifulTable()
x.append_row(["0", "a\nb"])
print(x)

Expected output

+---+---+
| 0 | a |
|   | b |
+---+---+

Actual Output

+---+-----+
| 0 | a
b |
+---+-----+

column_widths doesn't appear to be working

The content and header names for my table are being wrapped. To avoid this, I'm setting table.column_widths, as per the docs, such as

table.column_widths = [30, 30, 30]

But it doesn't seem to have any effect.

Is there are more correct way to establish column widths?

Is there a way not to print Column Headers

Hi there - thank you for a great product.
I have table of data that is formatted just perfectly HOWEVER I do NOT want the column headers to be printed.
Is there a way I can stop the column headers from being printed.

Thank you very much

PJ

Corrupted table view with long table

#!/usr/bin/env python3

from beautifultable import BeautifulTable

table = BeautifulTable()
table.column_headers = list(["Name" for x in range(100)])
table.append_row(list(["Name" for x in range(100)]))

print(table)

Become to:

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na | Na |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

row_count would be very helpful to have

First, thanks for the awesome tool! I'm just getting started with Python, so I'm not quite ready to figure out how to add this myself, but would it be possible to add a row_count method, similar to column_count?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.