472,779 Members | 2,779 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.

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 3218

[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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
2
by: Malcolm Dew-Jones | last post by:
I am looking at xslt 1.0 and trying to understand if empty text nodes are supposed to be stripped or not as the default behaviour. 3.4 starts by listing rules for when white space is not stripped...
17
by: Stanimir Stamenkov | last post by:
Is it possible to make two inline elements to appear adjacent stripping any white space appearing in between in the source? Example: <span class="adj">1</span> <span class="adj">2</span>...
11
by: gopal srinivasan | last post by:
Hi, I have a text like this - "This is a message containing tabs and white spaces" Now this text contains tabs and white spaces. I want remove the tabs and white...
3
by: Prince | last post by:
I have some <RequiredFieldValidator> on my page and everything works fine except that there are lots of white spaces between the web server controls that are being validated. I've set the Display...
2
by: John Daly | last post by:
I have data comming out of a stored procedure with embeded spaces. After binding the data, it reomves ALL white-space except for 1 space. How can I get the spaces to remain? For example This is...
12
by: JA | last post by:
Is there a way to remove all the white space in the fields? I have been using Find-and-replace - looking for 2 or 3 or 4 or 10 spaces and replacing them with none. I don't want to replace single...
5
by: shajias | last post by:
Hi all, Suppose I am having a string like this. mystr = " I have five spaces after this and 3 spaces after this and 10 spaces after this. How to remove this muliple...
2
by: delyan.nestorov | last post by:
Hi All, I have the following problem: I read lines from DXF file ( AutoCAD format file ). Then I need to remove white spaces from lines to continue working on data i.e. converting from string...
0
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
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: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
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 ...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
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.