473,386 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Structured writing to console, such as a table

Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all the items in a string
do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined up in a console.
So:
Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was waiting for me.
A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips, references, examples...
Thanks,
Vincent

Jul 18 '05 #1
3 3595
Raaijmakers, Vincent (IndSys, GE Interlogix) wrote:
Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where
all the items in a string do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined
up in a console. So:
Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was
waiting for me. A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips,
references, examples...


This is not a solution to your problem, but is something that you
may want to know. Docutils and the reStructuredText that it
processes support the kind of ASCII tables that you describe. You
may want to check the Docutils/reStructuredText specification. If
you follow that specification you will be able to send your
tables through a Docutil tool to produces HTML, LaTeX, etc.

Docutils, by the way, is implemented in Python.

See:

http://docutils.sourceforge.net/docs...ef.html#tables
http://docutils.sourceforge.net/
https://sourceforge.net/projects/docutils/

Dave

--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dk******@rexx.com
Jul 18 '05 #2
"Raaijmakers, Vincent (IndSys, GE Interlogix)" <Vi*****************@ge.com> writes:
Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all
the items in a string do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined
up in a console. So:
Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was
waiting for me. A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips,
references, examples...


This is going to sound unhelpful, but I suspect the problem is that
the problem is too simple - everyone *does* reinvent the wheel,
because it's faster than going to find a generic solution.

Having said that, I didn't manage to quickly write some code for you
:-)

The first question is, what does your data look like? From your
example, I'd say that you have a list of items

items = ["a", "bbbbbbbbb", "cc"]

but I'm not sure how you get your values.

Let's assume that in fact you have a "list of rows" type of
representation:

rows = [["a", 1, 2],
["bbbbbbbbb", 2, 17],
["cc", 3, 5]
]

This may or may not match your requirements, but you should be able to
either adapt my code or your data as needed.

The first problem is working out the column widths you need. That's
not difficult, just messy (because in some senses, the data is "the
wrong way round" - a list of coumns would be better for this step, but
worse later on).

def column_widths(titles, rows):
'''Calculate column widths for a "list of rows"'''

# Initialise widths to have all columns zero width to start with
widths = [len(str(title)) for title in titles]

# Adjust the width to allow space for each row in turn
for row in rows:
widths = [max(w, len(str(item)))
for w, item in zip(widths, row)]

return widths

That's a bit messy, so let's dissect it. I use list comprehensions a
lot here - if you don't know how they work, it's well worth studying
them.

We start by setting widths to fit the titles. We assume that all rows
have the same number of elements - I don't check for this.

Then, for each row, we adjust the widths to fit the items in that row.
The list comprehension goes through each column, and the new width of
that column is either the old width (if the new item fits already) or
the length of the new item (if it is the biggest so far).

For each item, we're calculating len(str(item)) which is the length of
the string representation of the item - ie, the space required on
screen for that item.

OK, that was the ugly bit - now we just format the results. This is
simple, but a little long winded.

def format(titles, rows):
"Format a table"

# First calculate the column widths
widths = column_widths(titles, rows)

# Create the result as a list of lines - it's more flexible
# than printing directly
result = []

# Title line first (add 3 spaces between colums)
line = ' '.join([t.ljust(w) for t, w in zip(titles, widths)])
result.append(line)

# Separator line (add -+- between columns)
line = '-+-'.join(['-' * w for w in widths])
result.append(line)

# Rows of data
for row in rows:
line = ' | '.join([item.ljust(w) for item, w in zip(row, widths)])
result.append(line)

return result

Now you can do:

print "\n".join(format(titles, rows))

I hope this helps. As I say, the problem is often that matching the
algorithm to what you really want is harder than writing the code in
the first place, so don't be afraid to play with this (it's nearly
midnight, so I'm offering no guarantees that this code is correct :-))

Paul
--
This signature intentionally left blank
Jul 18 '05 #3
"Raaijmakers, Vincent (IndSys, GE Interlogix)" <Vi*****************@ge.com> wrote in message news:<ma**********************************@python. org>...
Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all the
items in a string
do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined up in
a console.
So:
Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was waiting
for me.
A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips, references,
examples...
Thanks,
Vincent


And here comes solution No. 123.999 of xxxxxxxxx solutions :==)))
col1_text=['a', 'bbbbbbbb', 'cc']
col2_text=['1', '2', '3']
col3_text=['2', '17', '5']
headers=['Item:', 'Value:', 'Another Value:'] def print_formatted(headers,cols): .... # len of list with headertext and
.... # len of list with columnstext must be equal
.... hl=len(headers)
.... cl=len(cols)
.... if cl <> hl:
.... print 'len(headers)=%d <> len(cols)=%d'%(hl,cl)
.... return
.... # An adhoc-function get the length of the longest text in list
.... max_strlen=lambda aList:reduce(lambda l,x:len(x)>l and len(x) or l,aList,0)
.... col_lens=[max_strlen(cols[i]+[headers[i]]) for i in range(cl)]
.... # Fomatstring for header
.... format= ('%%-%ds '*cl)%tuple(col_lens)
.... print format%tuple(headers)
.... # Formatstring to underline the headertext ----+------+----
.... under_line= '-+-'.join(['-'*col_lens[i] for i in range(cl)])
.... print under_line
.... # Formatstring for the textlines
.... format = ' | '.join(['%%-%ds'%col_lens[i] for i in range(cl)])
.... for line in zip(*cols):
.... print format%line
....
print_formatted(headers,[col1_text,col2_text,col3_text])
Item: Value: Another Value:
---------+--------+---------------
a | 1 | 2
bbbbbbbb | 2 | 17
cc | 3 | 5


Regards
Peter
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Edmond Neo | last post by:
I use structured storage to store large amounts of data in various streams. I realize that I can call structured storage through a wrapper in .NET, but I'm concerned that there is a performance...
4
by: nekiv90 | last post by:
Greetings, I was able to create the structured type: CREATE TYPE address_t AS ( street char(30), city char(15), state char(10), postcode smallint ) MODE...
3
by: _link98 | last post by:
Running DB2 ESE V8.1.8 on WinXP. This is Fixpak 8. Have a structured-type and some methods for that type. One of my methods needs to do insert / update on tables. The type specification...
3
by: HALLES | last post by:
HELLO ! in upper case: i mean to be heard ;o) Compilers are good ! Myself, i used TP6 and TP7 to work on dBASE V files, once ... a long time ago. I was unaware of Internet Usenet world,...
3
by: Marius Rus | last post by:
I have a project in C# that do the followings: From an csv text file it is taking datas and inserted into an paradox database. My problem it is that when writing into the paradox database it is...
2
by: John Salerno | last post by:
I wrote this code just to experiment with writing to and reading from a file. It seems to work fine when writing, but when reading the file, it only prints the filepath to the screen, not the file...
4
by: Troy | last post by:
We recently installed the .Net framework on a windows 2000 server. Shortly after that we experienced intermitant problems running a web based program that accesses an Access 2002 database. The...
7
by: gordy | last post by:
Hey all, I have a fairly simple app which goes out to the web to download data. I want to store this data in a database (1 table, ~8 fields or so). My program is written in VB.net and works...
12
by: Steve | last post by:
I have been studying the Adjacency List Model as a means of achieving a folder structure in a project I am working on. Started with the excellent article by Gijs Van Tulder ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.