[Tutor] using python for parsing

Walter Prins wprins at gmail.com
Wed Jul 10 15:27:27 CEST 2013


Hello,


On 29 June 2013 19:00, Makarand Datar <datar at wisc.edu> wrote:

> Hi,
>
> So I am able to read in a file, and write out a file from python. I have
> some question about the text manipulation that I need to do between reading
> in a file and spitting out another. Couple of things I would like to do,
> are: if the first character of a line is a comma, I would like to delete
> the newline character at the end of the previous line and make a longer
> line (one line followed by another without a newline in between); if the
> first character of the line is an exclamation mark, I would like to delete
> that line altogether. So for instance, if the input file text looks like
> the following,
>
> one, two, three
> , four, five, six
> ! This is a comment
> seven, eight, nine
>
> I would like to output a file the text in which looks like
>
> one, two, three, four, five, six
> seven, eight, nine
>

Try this:

import re

input_str = """
one, two, three
, four, five, six
! This is a comment
seven, eight, nine
"""

# Join lines ending in trailing commas:
input_str = re.sub('\n,', '', input_str)
# Remove comment lines starting with !
input_str = re.sub('!.*\n', '', input_str)


print input_str


Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130710/50a99f72/attachment.html>


More information about the Tutor mailing list