472,779 Members | 2,461 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Formatting a string to be a columned block of text

Hi,

I'm creating a python script that can take a string and print it to the
screen as a simple multi-columned block of mono-spaced, unhyphenated
text based on a specified character width and line hight for a column.
For example, if i fed the script an an essay, it would format the text
like a newspaper on the screen. Text processing is very new to me, any
ideas on how I could achieve a multi-columned text formatter. Are there
any libraries that already do this?

Thanks and happy holidays!
Leon

Dec 26 '06 #1
7 2601

Leon wrote:
Hi,

I'm creating a python script that can take a string and print it to the
screen as a simple multi-columned block of mono-spaced, unhyphenated
text based on a specified character width and line hight for a column.
For example, if i fed the script an an essay, it would format the text
like a newspaper on the screen. Text processing is very new to me, any
ideas on how I could achieve a multi-columned text formatter. Are there
any libraries that already do this?

Thanks and happy holidays!
Leon
I did something similar, read in text file format it to 79 characters
and print it out to a multiple images of 480x272 so i could read them
on my PSP. Anyway the code to handle the formatting (even though this
is one column of 78 characters with one character space from the top
and bottom, and sides)

corpus = open("essay.txt","r")

wordcount = 0
pctline = ""
pctlines = [

for line in corpus.readlines():
# i dont need the newline character as it will be printed onto
images
line = line[:-1]

# i want individual words where each word is separated by a space
character
words = line.split(" ")

for word in words:
if wordcount + len(word) + 1 < 78:
wordcount = wordcount + len(word) + 1
pctline = pctline + word + " "
else:
wordcount = len(word)

pctlines.append(pctline)
pctline = None
pctline = word + " "

corpus.close()

what it does is keeps a list of words and iterate through it and see if
the length of that word and one space character and the line doesn't
exceed 78, if it doesnt then add it to the pctlines, add the count to
the wordcount + 1. If it does then we have one line either 78
characters long or less and add it to pctlines which is a list of all
the lines.

Hope this helps.
Cheers

Dec 26 '06 #2
"Leon" <pe******@gmail.comwrote in message
news:11**********************@h40g2000cwb.googlegr oups.com...
Hi,

I'm creating a python script that can take a string and print it to the
screen as a simple multi-columned block of mono-spaced, unhyphenated
text based on a specified character width and line hight for a column.
For example, if i fed the script an an essay, it would format the text
like a newspaper on the screen. Text processing is very new to me, any
ideas on how I could achieve a multi-columned text formatter. Are there
any libraries that already do this?

Thanks and happy holidays!
Leon
Check out the textwrap module, new in 2.3. Here is code to do one- and
two-column output.

-- Paul
gettysburgAddress = """Four score and seven years ago our fathers brought
forth on this continent, a new nation, conceived in Liberty, and dedicated
to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any
nation so conceived and so dedicated, can long endure. We are met on a great
battle-field of that war. We have come to dedicate a portion of that field,
as a final resting place for those who here gave their lives that that
nation might live. It is altogether fitting and proper that we should do
this.
But, in a larger sense, we can not dedicate -- we can not consecrate -- we
can not hallow -- this ground. The brave men, living and dead, who struggled
here, have consecrated it, far above our poor power to add or detract. The
world will little note, nor long remember what we say here, but it can never
forget what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far so
nobly advanced. It is rather for us to be here dedicated to the great task
remaining before us -- that from these honored dead we take increased
devotion to that cause for which they gave the last full measure of
devotion -- that we here highly resolve that these dead shall not have died
in vain -- that this nation, under God, shall have a new birth of freedom --
and that government of the people, by the people, for the people, shall not
perish from the earth.
""".split('\n')

import textwrap

# wrap text at 50 characters
for line in gettysburgAddress:
print "\n".join( textwrap.wrap(line,50) )
print

# create two columns of text
wrappedLines = sum([ textwrap.wrap(line,35) + ['']
for line in gettysburgAddress ],[])[:-1]
numLines = len(wrappedLines)
halfway = numLines/2
twoCol = [ "%-38s%s" % pair for pair in
zip(wrappedLines[:halfway],wrappedLines[halfway:]) ]
print "\n".join(twoCol)

Dec 26 '06 #3
On 26 Dec 2006 04:14:27 -0800, Leon <pe******@gmail.comwrote:
I'm creating a python script that can take a string and print it to the
screen as a simple multi-columned block of mono-spaced, unhyphenated
text based on a specified character width and line hight for a column.
Hi, Leon,
For putting the columns together zip is your friend. Let me lay out an example:

# get your text and strip the newlines:
testdata = file('something').read().replace('\n','')
# set some parameters (these are arbitrary, pick what you need)::
colwidth = 35
colheight = 20
numcol = 2
rowperpage = colheight * numcol
# first split into lines (this ignores word boundaries
# you might want to use somehting more like placid posted for this)
data1 = [testdata[x:x+colwidth] for x in range(0,len(testdata),colwidth)]
# next pad out the list to be an even number of rows - this will give
# a short final column. If you want them balanced you're on your own ;)
data1.extend(['' for x in range(rowsperpage - len(data1) % rowsperpage)])
# then split up the list based on the column length you want:
data2 = [data1[x:x+colheight] for x in range(0,len(data1),colheight)]
# then use zip to transpose the lists into columns
pages = [zip(*data2[x:x+numcol]) for x in range(0,len(data2),numcol)]
# finally unpack this data with some loops and print:
for page in pages:
for line in page:
for column in line:
print ' %s ' % column, #<- note the comma keeps newlines out
print '\n'
print '\f'
-dave
Dec 26 '06 #4
Thanks, Paul. I didn't know about textwrap, that's neat.

Leon,
so in my example change
data1= [testdata[x:x+colwidth] for x in range(0,len(testdata),colwidth)]
to
data1 = textwrap.wrap(testdata,colwidth)
data1 = [x.ljust(colwidth) for x in data1]
oh and I made a mistake that double spaces it. the "print '\n'"
line needs to be either
print ''
or
print '\n',
(with a comma)

-dave
Dec 26 '06 #5
"Paul McGuire" <pt***@austin.rr._bogus_.comwrote in message
news:45***********************@roadrunner.com...
>
gettysburgAddress = """Four score and seven years ago...
<snip>

By the way, this variable contains only 3 (very long) lines of text, one for
each paragraph. (Not immediately obvious after Usenet wraps the text.)

-- Paul
Dec 26 '06 #6
"Paul McGuire" <pt***@austin.rr._bogus_.comwrote:
By the way, this variable contains only 3 (very long) lines of text,
one for each paragraph. (Not immediately obvious after Usenet wraps
the text.)
Usenet doesn't wrap text, all it has is a convention which suggests that
people posting to usenet should wrap their text at 72 characters. Your
newsreader probably wrapped the text for you when you were posting, but
for deliberately long lines many newsreaders will have an option
somewhere to turn off the text wrapping (and the reader probably also
has to turn off text wrapping when they read it).

For source code where you want long unwrapped strings you would have
been better to do the text wrapping in an editor first and use backslash
line continuations.

e.g.
gettysburgAddress = """\
Four score and seven years ago our fathers brought forth on this \
continent, a new nation, conceived in Liberty, and dedicated to the \
proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, \
or any nation so conceived and so dedicated, can long endure. We are \
met on a great battle-field of that war. We have come to dedicate a \
portion of that field, as a final resting place for those who here \
gave their lives that that nation might live. It is altogether fitting \
and proper that we should do this.
But, in a larger sense, we can not dedicate -- we can not consecrate \
-- we can not hallow -- this ground. The brave men, living and dead, \
who struggled here, have consecrated it, far above our poor power to \
add or detract. The world will little note, nor long remember what we \
say here, but it can never forget what they did here. It is for us the \
living, rather, to be dedicated here to the unfinished work which they \
who fought here have thus far so nobly advanced. It is rather for us \
to be here dedicated to the great task remaining before us -- that \
from these honored dead we take increased devotion to that cause for \
which they gave the last full measure of devotion -- that we here \
highly resolve that these dead shall not have died in vain -- that \
this nation, under God, shall have a new birth of freedom -- and that \
government of the people, by the people, for the people, shall not \
perish from the earth.\
""".split('\n')
Dec 26 '06 #7
"Dave Borne" <db****@gmail.comwrote in
news:ma***************************************@pyt hon.org:
Thanks, Paul. I didn't know about textwrap, that's neat.

Leon,
so in my example change
>data1= [testdata[x:x+colwidth] for x in
range(0,len(testdata),colwidth)]
to
>data1 = textwrap.wrap(testdata,colwidth)
data1 = [x.ljust(colwidth) for x in data1]

oh and I made a mistake that double spaces it. the "print '\n'"
line needs to be either
print ''
or
print '\n',
(with a comma)
The solutions so far serve up text that is split within the
confines of the column width, but leave a "ragged right" margin,
where the line lengths appear to differ. I had the impression that
the OP wanted right-and-left justified text, such as would
typically be found in a newspaper column. Here's a shot at doing
that for fixed-width fonts. To use it, first split your lines as
others have suggested, then print aline(line,colwid) for each line
in your data.

# aline - align text to fit in specified width
# This module arbitrarily chooses to operate only on long-enough
# lines, where "long-enough" is defined as 60% of the specified
# width in this case.
#
def aline(line, wid):
line = line.strip()
lnlen = len(line)
if wid lnlen wid*0.6:
ls = line.split()
diff = wid - lnlen
#nspaces = len(ls)-1
eix = 1
bix = 1
while diff 0: # and nspaces 0:
if len(ls[bix]) == 0 or ls[bix].find(' ') >= 0:
ls[bix] += ' '
else:
ls.insert(bix,'')
diff -= 1
bix += 2
if bix >= 1+len(ls)/2: bix = 1

if diff 0:
if len(ls[-eix]) == 0 or ls[-eix].find(' ') >= 0:
ls[-eix] += ' '
else:
ls.insert(-eix,'')
diff -= 1
eix += 2
if eix >= 1+len(ls)/2: eix = 1
line = ' '.join(ls)
return line

--
rzed
Dec 26 '06 #8

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

Similar topics

4
by: Lorentz | last post by:
Greetings. I have a process that takes data from a MS Access2000 database and produces .pdf files. Everything works fine... but I'm trying to format the header and footer of the pdf file so...
7
by: ilona | last post by:
Hi all, I store phone numbers in the database as 123447775665554(input mask is used for input, and some numbers have extensions), and I also know from db if the number is Canadian, US, or some...
7
by: Matthew Wieder | last post by:
Hi - I have a datagrid that has a black header and the rows alternate white and gray. The problem is that until items are added to the grid, the grid appears as a large black rectangle, which is...
4
by: hope | last post by:
Hi, How can I format a string field using Data Formatting Expression property in datagrid? For example: format last name from BROWN to Brown. Thanks
8
by: G.Ashok | last post by:
Hi, I have created CultureInfo object and specified required digit grouping in it. The one of the overloaded ToString methods of Decimal type has parameters to format the value with required...
25
by: mdh | last post by:
Hi Group, Not looking for an answer, but more of an explanation. Thinking back to those heady days when you had the time to do them, may I ask this. Exercise 1-22 asks for a program to "fold"...
9
by: sck10 | last post by:
Hello, I have a page with an ImageButton that is used to redirect to another page. When the page first opens, everything looks as expected. However, when I click on the image, the new page...
14
by: Scott M. | last post by:
Ok, this is driving me nuts... I am using VS.NET 2003 and trying to take an item out of a row in a loosely-typed dataset and place it in a label as a currency. As it is now, I am getting my...
7
by: Andy_Khosravi | last post by:
I use the formatting trick in A97 to simulate conditional formatting in continuous forms. It has, up to this point, worked fine. Today I was making some design changes to the parent form (the...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.