Strip white spaces from source

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • qwweeeit@yahoo.it

    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.acc eptsCards ( self, from_stack, cards
    )
    must be reduced to:
    .. . max_move and AC_RowStack.acc eptsCards(self, from_stack,card s)

    My solution has been (wrogly): ''.join(source_ line.split())
    which gives:
    max_moveandAC_R owStack.accepts Cards(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.

  • Richie Hindle

    #2
    Re: Strip white spaces from source


    [qwweeeit][color=blue]
    > 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.acc eptsCards ( self, from_stack, cards
    > )
    > must be reduced to:
    > . . max_move and AC_RowStack.acc eptsCards(self, from_stack,card s)[/color]

    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.tokeni ze
    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.tok enize 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.writ e( match.group( 1 ) )
    sys.stdout.writ e( 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.writ e( line[ self.last_ecol: scol ] )

    # Print the token itself.
    sys.stdout.writ e( 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.writ e( self.line )


    if __name__ == '__main__':
    if len( sys.argv ) != 2:
    print __doc__
    else:
    file = open( sys.argv[ 1 ], 'rt' )
    unSpace = UnSpace()
    tokenize.tokeni ze( file.readline, unSpace.onToken )
    unSpace.flush()

    --
    Richie Hindle
    richie@entrian. com

    Comment

    • qwweeeit@yahoo.it

      #3
      Re: Strip white spaces from source

      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.gener ate_tokens(cStr ingIO.StringIO( string).readlin e" 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.

      Comment

      • Richie Hindle

        #4
        Re: Strip white spaces from source


        [qwweeeit][color=blue]
        > If someone is interested (I think nobody...) I can give my solution.[/color]

        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
        richie@entrian. com

        Comment

        • qwweeeit@yahoo.it

          #5
          Re: Strip white spaces from source

          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.genera te_tokens(cStri ngIO.StringIO(s Line).readline) :
          .. . if x[0]==50:
          .. . . sLine=sLine.rep lace(' '+x[1],x[1])
          .. . . sLine=sLine.rep lace(x[1]+' ',x[1])
          except tokenize.TokenE rror:
          .. 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.

          Comment

          • William Park

            #6
            Re: Strip white spaces from source

            qwweeeit@yahoo. it wrote:[color=blue]
            > 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.acc eptsCards ( self, from_stack, cards
            > )
            > must be reduced to:
            > . . max_move and AC_RowStack.acc eptsCards(self, from_stack,card s)
            >
            > My solution has been (wrogly): ''.join(source_ line.split())
            > which gives:
            > max_moveandAC_R owStack.accepts Cards(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.[/color]

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

            --
            William Park <opengeometry@y ahoo.ca>, Toronto, Canada
            ThinFlash: Linux thin-client on USB key (flash) drive

            Comment

            Working...