[Tutor] re help

Jacob S. keridee at jayco.net
Mon Mar 14 23:04:33 CET 2005


And I wouldn't mind mentioning that re is slightly over kill for the 
examples given.
Try this.

#######################################

old_group_delimiter = "\n\n"
old_line_delimiter = "\n"
new_group_delimiter = "\n"
new_line_delimiter = ", "

fi = raw_input("Input file to use? ")
fi = open(fi,"r")
stuff = fi.read()
fi.close()
addressgroups = stuff.split(old_group_delimiter)
addressgroups = [x.split(old_line_delimiter) for x in addressgroups]
addressgroups = [new_line_delimiter.join(x) for x in addressgroups]
newtext = new_group_delimiter.join(addressgroups)

fi = raw_input("Output file to use? ")
fi = open(fi,"w")
fi.write(newtext)
fi.close()

#######################################

But your probably using re to study it, though. Just an alternative option.
I'm trying to keep all the different ways in my head you know...

Jacob S.

> The following program takes text data like this:
> Jimi Hendrix
> 2100 South Ave
> Seattle, WA 55408
>
> and changes it to this
>
> Jimi Hendrix, 2100 South Ave,Seattle,WA,55488
>
> and writes it to a file. The problem I'm running into
> is that it only writes this first address to a file
> and there are several others in the file. I believe it
> has something to do with using re.search instead of
> re.findall. But re.findall returns a error when I try
> using it. Suggestions? Thanks in advance.
> Here is the script:
>
> import re
> f = open('reformat.txt').read()
> pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*)
> ([^\r\n]*) ([^\r\n]*)")
> x=re.search(pat,f)
> name = x.group(1)
> address = x.group(2)
> citystate = x.group(3)+x.group(4)
> zipcd = x.group(5)
> o= open('reformat1.txt','w')
> o.write("%s,%s,%s,%s\n" % (name, address,
> citystate,zipcd))
> o.close()
> print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd))
>
>
>
> __________________________________
> Do you Yahoo!?
> Yahoo! Small Business - Try our new resources site!
> http://smallbusiness.yahoo.com/resources/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list