[Tutor] Is there a better way?

Marco Casazza marco.vincenzo at gmail.com
Wed Jan 11 13:34:53 CET 2012


Hello,

I've been slowly teaching myself python, using it for small projects 
when it seems appropriate. In this case, I was handed a list of email 
addresses for a mailing but some of them had been truncated. There are 
only 21 possible email "suffixes" so I planned to just identify which it 
should be and then replace it. However, when I started writing the code 
I realized that I'd be doing a lot of "repeating". Is there a better way 
to "fix" the suffixes without doing each individually? Here's my working 
code (for 4 colleges):

import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
     outlist = []
     for line in infile.read().split('\n'):
         if line.rstrip().lower().endswith('edu'):
             newline = line + '\n'
             outlist.append(newline.lower())
         elif re.search("@bar", line):
             newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@bcc", line):
             newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@bmc", line):
             newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
             outlist.append(newline.lower())
         elif re.search("@leh", line):
             newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
             outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
     outfile.writelines(outlist)

Thanks,
Marco


More information about the Tutor mailing list