Split with python

Discussion in 'Python' started by Norman Khine, Aug 29, 2006.

  1. Norman Khine

    Norman Khine Guest

    Hello,
    I have a csv file which is has a field that has something like:

    text.csv
    "text (xxx)"
    "text (text) (yyy)"
    "text (text) (text) (zzz)"

    I would like to split the last '(text)' out and put it in a new column,
    so that I get:

    new_test.csv
    "text","(xxx)"
    "text (text)","(yyy)"
    "text (text) (text)","(zzz)"

    how can this be done?

    Thanks

    Norman
     
    Norman Khine, Aug 29, 2006
    #1
    1. Advertising

  2. Norman Khine

    Guest

    Norman Khine:
    > I have a csv file which is has a field that has something like:
    > "text (xxx)"
    > "text (text) (yyy)"
    > "text (text) (text) (zzz)"
    >
    > I would like to split the last '(text)' out and put it in a new column,
    > so that I get:
    > "text","(xxx)"
    > "text (text)","(yyy)"
    > "text (text) (text)","(zzz)"



    Maybe something like this can be useful, after few improvements (RE
    formatting is a work in progress):

    from StringIO import StringIO
    import re

    datain = StringIO("""
    "text (xxx)"
    "text (text) (yy y) "
    "text (text) (text) ( zzz ) "
    """)


    lastone = re.compile("""
    \s* ( \(
    [^()"]*
    \)
    \s* "
    )
    \s* $
    """, re.VERBOSE)

    def repl(mobj):
    txt_found = mobj.groups()[0]
    return '", "' + txt_found

    for line in datain:
    line2 = line.strip()
    if line2:
    print lastone.sub(repl, line2)

    """
    The output is:

    "text", "(xxx)"
    "text (text)", "(yy y) "
    "text (text) (text)", "( zzz ) "

    """


    Bye,
    bearophile
     
    , Aug 30, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    475
  2. Carlos Ribeiro
    Replies:
    11
    Views:
    712
    Alex Martelli
    Sep 17, 2004
  3. trans.  (T. Onoma)

    split on '' (and another for split -1)

    trans. (T. Onoma), Dec 27, 2004, in forum: Ruby
    Replies:
    10
    Views:
    226
    Florian Gross
    Dec 28, 2004
  4. Sam Kong
    Replies:
    5
    Views:
    255
    Rick DeNatale
    Aug 12, 2006
  5. Stanley Xu
    Replies:
    2
    Views:
    638
    Stanley Xu
    Mar 23, 2011
Loading...

Share This Page