Parsing text

Scott David Daniels scott.daniels at acm.org
Tue Dec 20 12:36:12 EST 2005


sicvic wrote:
> Not homework...not even in school (do any universities even teach
> classes using python?). 
Yup, at least 6, and 20 wouldn't surprise me.

> The code I currently have looks something like this:
> ...
> f = open(sys.argv[1]) #opens output file
> #loop that goes through all lines and parses specified text
> for line in f.readlines():
>     if  re.search(r'Person: Jimmy', line):
> 	person_jimmy.write(line)
>     elif re.search(r'Person: Sarah', line):
> 	person_sarah.write(line)
Using re here seems pretty excessive.
How about:
     ...
     f = open(sys.argv[1])  # opens input file ### get comments right
     source = iter(f)  # files serve lines at their own pace.  Let them
     for line in source:
         if line.endswith('Person: Jimmy\n'):
             dest = person_jimmy
         elif line.endswith('Person: Sarah\n'):
             dest = person_sarah
         else:
             continue
         while line != '---------------\n':
             dest.write(line)
             line = source.next()
     f.close()
     person_jimmy.close()
     person_sarah.close()

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list