473,396 Members | 1,816 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,396 software developers and data experts.

HTML/text formatting question

I have a tool that outputs data in either html or text output.

Currently I'm writing chucnks like:

if html:
print '<html><body bgcolor="FFFFCC">'
print '<table border="1" bgcolor="CCCCFF" width="800">'
print '<tr><td colspan="2"><h2>'
print 'Differences %s: %s' % (htypestr, lbl1)
if html:
...

This seems clunky and my next step was going to be to define generic
functions which would generate the surrounding html tags only when
passed the proper argument. I was wondering if there was a better way
to do this with a standard Python library. It looked like formatter
might but that it also might be too low-level.

Any help is appreciated,
Jeff

Aug 3 '05 #1
2 1419
Dr. Who wrote:
I have a tool that outputs data in either html or text output.

Currently I'm writing chucnks like:

if html:
print '<html><body bgcolor="FFFFCC">'
print '<table border="1" bgcolor="CCCCFF" width="800">'
print '<tr><td colspan="2"><h2>'
print 'Differences %s: %s' % (htypestr, lbl1)
if html:
...


I'd create two Formatter classes, one for HTML and one for text. It
looks like, in your case, the HTML one should inherit from the text one.
Something like:

py> class TextFormatter(object):
.... def print_differences(self, htypestr, lbll):
.... print 'Differences %s: %s' % (htypestr, lbll)
....
py> class HTMLFormatter(TextFormatter):
.... def print_differences(self, htypestr, lbll):
.... print '<html><body bgcolor="FFFFCC">'
.... print '<table border="1" bgcolor="CCCCFF" width="800">'
.... print '<tr><td colspan="2"><h2>'
.... super(HTMLFormatter, self).print_differences(htypestr, lbll)
.... print '</h2></td></tr></table></body></html>'
....
py> formatter = TextFormatter()
py> formatter.print_differences('test', 'one')
Differences test: one
py> formatter = HTMLFormatter()
py> formatter.print_differences('test', 'one')
<html><body bgcolor="FFFFCC">
<table border="1" bgcolor="CCCCFF" width="800">
<tr><td colspan="2"><h2>
Differences test: one
</h2></td></tr></table></body></html>

Using this strategy, you would replace all your print statements with
calls to a formatter object. Which formatter you use would be
determined wherever you currently set 'html' to True or False.

HTH,

STeVe
Aug 3 '05 #2
"Dr. Who" <go****@spiceaid.com> writes:
This seems clunky and my next step was going to be to define generic
functions which would generate the surrounding html tags only when
passed the proper argument. I was wondering if there was a better way
to do this with a standard Python library. It looked like formatter
might but that it also might be too low-level.


You could use something like this:

class HTMLFormatter:

def __init__(self, tag, contents=None, **kwargs):

self.tag = tag
self._content = contents
self.attrs = dict()

self._set_attrs(kwargs)

def _set_attrs(self, attrs):

self.attrs = attrs

if '_class' in self.attrs:
self.attrs['class'] = self.attrs['_class']
del self.attrs['_class']

def set_content(self, contents, **kwargs):
"""
Set content of HTML element to contents.
f = HTMLFormatter('a')
f.set_content('cat', href='http://www.cat.org')
str(f) '<a href="http://www.cat.org">cat</a>' str(HTMLFormatter('td', 'cat')) '<td>cat</td>' str(HTMLFormatter('p', 'kitty kit', _class='cat')) '<p class="cat">kitty kit</p>' str(HTMLFormatter('br')) '<br/>'
"""

self._content = contents

if kwargs:
self._set_attrs(kwargs)

def set_attribute(self, attr, val):
"""Set/update attribute 'attr' to 'val'."""

self.attrs[attr] = val

def add_content(self, contents):
"""Add content to element.
p = HTMLFormatter('p', 'name of the cat is ')
p.add_content('meow')
str(p) '<p>name of the cat is meow</p>' p = HTMLFormatter('td')
p.add_content('cat')
str(p) '<td>cat</td>'
"""

if self._content is None:
self._content = ''

self._content = "%s%s" % (self._content, str(contents))

def contents(self):
"""Get contents of object.
p = HTMLFormatter('p', 'nice doggy dog')
p.contents() 'nice doggy dog' p.add_content(HTMLFormatter('em', 'called wuff'))
p.contents()

'nice doggy dog<em>called wuff</em>'

"""

return self._content

def __str__(self):
open_tag = '%s' % self.tag
if self.attrs:
attrs = self.attrs.items()
attrs.sort()
attrs_str = ' '.join(['%s="%s"' % (k, v) \
for k,v in attrs])
open_tag = '%s %s' % (self.tag, attrs_str)

if self._content is not None:
return '<%s>%s</%s>' % (open_tag, self._content, self.tag)
else:
return '<%s/>' % open_tag
Doctest strings show examples how to use it. For serious HTML building stuff
it needs fiddling with, but should be handy for tiny projects.

--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737 469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
Aug 25 '05 #3

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

Similar topics

8
by: Seth | last post by:
How can I completely turn off the auto formatting of Html in Visual Studio 7? I have tried all possible combinations (at least I think I have) of the Tools / Options / Text Editor / HTML XML /...
10
by: st4 | last post by:
Help, As part of my family history web site i need to get 150 pages of typed text into some format to display. It just text right now but I would like to add some graphics (photos) and make the...
258
by: Terry Andersen | last post by:
If I have: struct one_{ unsigned int one_1; unsigned short one_2; unsigned short one_3; }; struct two_{ unsigned int two_1;
3
by: Rigga | last post by:
Hi all, Firstly, sorry for the simple question, as i'm sure i'm missing something obvious. I have a text field (varchar) I am reading from an SQL db, into a string variable, in .NET I am...
8
by: Brian | last post by:
I was wondering if anyone here on the group could point me in a direction that would expllaing how to use python to convert a tsv file to html. I have been searching for a resource but have only...
8
by: CM | last post by:
Hi, Could anyone please help me? I am completing my Master's Degree and need to reproduce a Webpage in Word. Aspects of the page are lost and some of the text goes. I would really appreciate it....
5
by: David Housman | last post by:
Hello, I'm trying to implement a navigation bar with a ul in css. The code is a template, but i'm customizing. I can handle just text in each block, but i want the first block to have an image...
2
by: edwinparker | last post by:
I'm currently working on a ASP.NET (C#) web application to process bids. Right now the user will enter in some rich text into a textbox (I'm using FreeTextBox for this) and the text gets saved as...
4
by: Andy Bell | last post by:
Can I stop asp.net from applying self closing tags? I am trying to generate an html 4.01 strict page rather than an xhtml page and the w3 validator is unhappy about asp.net automatically...
3
by: realmerl | last post by:
Hi All. I'm trying to transform a html document into plain text via xslt. Simple you say! (i hope) I have got it working, by using the magnificent <xsl:value-of select="."/>. This returns the...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.