Strip white spaces from source

Q

qwweeeit

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_stack,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.
 
R

Richie Hindle

[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()
 
Q

qwweeeit

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(string).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.
 
R

Richie Hindle

[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*.
 
Q

qwweeeit

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.
 
W

William Park

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_stack,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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top