Escaping commas within parens in CSV parsing?

William Park opengeometry at yahoo.ca
Sun Jul 3 21:50:53 EDT 2005


felciano <felciano at gmail.com> wrote:
> Thanks for all the postings. I can't change delimiter in the source
> itself, so I'm doing it temporarily just to handle the escaping:
> 
> def splitWithEscapedCommasInParens(s, trim=False):
>         pat = re.compile(r"(.+?\([^\(\),]*?),(.+?\).*)")
>         while pat.search(s):
>                 s = re.sub(pat,r"\1|\2",s)
>         if trim:
>                 return [string.strip(string.replace(x,"|",",")) for x in
> string.split(s,",")]
>         else:
>                 return [string.replace(x,"|",",") for x in string.split(s,",")]
> 
> Probably not the most efficient, but its "the simplest thing that
> works" for me :-)
> 
> Thanks again for all the quick responses.

How about changing '(' or ')' into three double-quotes '"""'?  That will
solve splitting issue.  But, I'm not sure how you would get back '(' or
')', without much coding.

-- 
William Park <opengeometry at yahoo.ca>, Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
	   http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
	  http://freshmeat.net/projects/bashdiff/



More information about the Python-list mailing list