[Tutor] re help

Hameed U. Khan hameed.u.khan at gmail.com
Mon Mar 14 08:12:29 CET 2005


Hi, Ron!
  I am also a newbie in programming. But after reading your problem i
decided to solve it as a homework :). But there are few things you
didn't mentioned. Does all the addresses in first file have same
format. What seperates those addresses in the file. Assuming that all
address are on 3 lines seperated by a blank line (The address file
should have a blank line after the last address otherwise it will not
read the last address). i have made the following program.

#!/usr/bin/python
# format.py

import re

f = open("reformat.txt").read()
pat = re.compile(r"((?:.*\n)+?\n)",re.M)
res = pat.findall(f)
out = open("reformat1.txt","w")

for addy in res:
  addy = ", ".join(addy[:-2].split("\n"))
  out.write(addy + "\n")
out.close()

# End


This program works fine on my Linux box. And hopefully it will work
too on Windows.
I would also ask other experienced programmers that is there any other
better way we can do it :).

Happy Programming.

On Sun, 13 Mar 2005 21:26:08 -0800 (PST), Ron Nixon <nixonron at yahoo.com> wrote:
> 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
> 


-- 
Regards,
Hameed U. Khan
Registered Linux User #: 354374
-
*Computer without Linux is just like the world without computer.*


More information about the Tutor mailing list