469,627 Members | 938 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,627 developers. It's quick & easy.

Strip white spaces from source

Hi all,
I need to limit as much as possible the lenght of a source line,
stripping white spaces (except indentation).
For example:
.. . max_move and AC_RowStack.acceptsCards ( self, from_stack, cards
)
must be reduced to:
.. . max_move and AC_RowStack.acceptsCards(self,from_stack,cards)

My solution has been (wrogly): ''.join(source_line.split())
which gives:
max_moveandAC_RowStack.acceptsCards(self,from_stac k,cards)

Without considering the stripping of indentation (not a big problem),
the problem is instead caused by the reserved words (like 'and').

Can you help me? Thanks.

Jul 19 '05 #1
5 3037

[qwweeeit]
I need to limit as much as possible the lenght of a source line,
stripping white spaces (except indentation).
For example:
. . max_move and AC_RowStack.acceptsCards ( self, from_stack, cards
)
must be reduced to:
. . max_move and AC_RowStack.acceptsCards(self,from_stack,cards)


Here's a script that does some of what you want (stripping whitespace within
the three types of brackets). It was written to make code more compliant with
the Python style guide.

------------------------------- unspace.py -------------------------------

"""Strips spaces from inside brackets in Python source code, turning
( this ) into (this) and [ 1, ( 2, 3 ) ] into [1, (2, 3)]. This makes
the code more compliant with the Python style guide. Usage:

unspace.py filename

Output goes to stdout.

This file is deliberately written with lots of spaces within brackets,
so you can use it as test input.
"""

import sys, re, token, tokenize

OPEN = [ '(', '[', '{' ]
CLOSE = [ ')', ']', '}' ]

class UnSpace:
"""Holds the state of the process; onToken is a tokenize.tokenize
callback.
"""
def __init__( self ):
self.line = None # The text of the current line.
self.number = -1 # The line number of the current line.
self.deleted = 0 # How many spaces have been deleted from 'line'.

self.last_srow = 0
self.last_scol = 0
self.last_erow = 0
self.last_ecol = 0
self.last_line = ''

def onToken( self, type, tok, ( srow, scol ), ( erow, ecol ), line ):
"""tokenize.tokenize callback."""
# Print trailing backslashes plus the indent for new lines.
if self.last_erow != srow:
match = re.search( r'(\s+\\\n)$', self.last_line )
if match:
sys.stdout.write( match.group( 1 ) )
sys.stdout.write( line[ :scol ] )

# Print intertoken whitespace except the stuff to strip.
if self.last_srow == srow and \
not ( self.last_type == token.OP and self.last_tok in OPEN ) and \
not ( type == token.OP and tok in CLOSE ):
sys.stdout.write( line[ self.last_ecol:scol ] )

# Print the token itself.
sys.stdout.write( tok )

# Remember the properties of this token.
self.last_srow, self.last_scol = ( srow, scol )
self.last_erow, self.last_ecol = ( erow, ecol )
self.last_type, self.last_tok = type, tok
self.last_line = line

def flush( self ):
if self.line is not None:
sys.stdout.write( self.line )
if __name__ == '__main__':
if len( sys.argv ) != 2:
print __doc__
else:
file = open( sys.argv[ 1 ], 'rt' )
unSpace = UnSpace()
tokenize.tokenize( file.readline, unSpace.onToken )
unSpace.flush()

--
Richie Hindle
ri****@entrian.com

Jul 19 '05 #2
Hi Richie,
thank you for your answer.
Your solution is interesting but does not take into account some white
spaces (like those after the commas, before or after mathematical
operands etc...).
Besides that I'm a almost a newbie in Python, and I have the very old
programmers' habits (I don't use classes...).

But I have solved nevertheless my problem (with the help of Alex
Martelli and his fab method of
"tokenize.generate_tokens(cStringIO.StringIO(strin g).readline" I have
read in a clp answer of Alex to a question of Gabor Navy).

If someone is interested (I think nobody...) I can give my solution.

Bye.

Jul 19 '05 #3

[qwweeeit]
If someone is interested (I think nobody...) I can give my solution.


I'd be interested to see it, certainly.

It's always a good idea to post your solution, if only for future reference.
It's frustrating to do a Google Groups search for a problem and find that
someone else has solved it but without saying *how*.

--
Richie Hindle
ri****@entrian.com

Jul 19 '05 #4
Hi Richie,
I did not post my solution because I did not want to "pollute" the
pythonic way of programming.
Young programmers, don't follow me!
I hate (because I am not able to use them...) classes and regular
expressions.
Instead I like lists, try/except (to limit or better eliminate
debugging) and os.system + shell programming (I use Linux).
The problem of stripping white spaces from python source lines could be
easily (not for me...) solved by RE.

Instead I choosed the hard way:
Imagine you have a lot of strings representing python source lines (in
my case I have almost 30000 lines).
Let's call a generic line "sLine" (with or without the white spaces
representing indentation).
To strip the un-necessary spaces you need to identify the operands.

Thanks to the advice of Alex Martelli, there is a parsing method based
on tokenize module, to achieve this:

import tokenize, cStringIO
try:
.. for x in
tokenize.generate_tokens(cStringIO.StringIO(sLine) .readline):
.. . if x[0]==50:
.. . . sLine=sLine.replace(' '+x[1],x[1])
.. . . sLine=sLine.replace(x[1]+' ',x[1])
except tokenize.TokenError:
.. pass

- x[0] is the 1st element of the x tuple, and 50 is the code for
OPERAND.
(For those who want to experiment on the x tuple, you can print it
merely by a
"print str(x)". You obtain as many tuples as the elements present in
the line).
- x[1] (the 2nd element of the x tuple) is the Operand itself.

The try/except is one of my bad habits:
the program fails if the line is a multiline.
Ask Alex... I haven't gone deeper.

At the end you have sLine with white spaces stripped...
There is yet a mistake...: this method strip white spaces also inside
strings.
(I don't care...).

A last word of caution: I haven't tested this extract from my
routine...

This small script is part of a bigger program: a cross-reference tool,
but don't ask me for that...

Bye.

Jul 19 '05 #5
qw******@yahoo.it wrote:
Hi all,
I need to limit as much as possible the lenght of a source line,
stripping white spaces (except indentation).
For example:
. . max_move and AC_RowStack.acceptsCards ( self, from_stack, cards
)
must be reduced to:
. . max_move and AC_RowStack.acceptsCards(self,from_stack,cards)

My solution has been (wrogly): ''.join(source_line.split())
which gives:
max_moveandAC_RowStack.acceptsCards(self,from_stac k,cards)

Without considering the stripping of indentation (not a big problem),
the problem is instead caused by the reserved words (like 'and').

Can you help me? Thanks.


Perhaps, you can make indent(1) do what you want. It's designed for C
program, but...

--
William Park <op**********@yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
http://home.eol.ca/~parkw/thinflash.html
Jul 19 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Stu Cazzo | last post: by
2 posts views Thread by Malcolm Dew-Jones | last post: by
17 posts views Thread by Stanimir Stamenkov | last post: by
11 posts views Thread by gopal srinivasan | last post: by
3 posts views Thread by Prince | last post: by
2 posts views Thread by John Daly | last post: by
12 posts views Thread by JA | last post: by
2 posts views Thread by delyan.nestorov | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.