473,416 Members | 1,541 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,416 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 2668

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...
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...
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...
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.