[Tutor] Text matching

Kent Johnson kent37 at tds.net
Fri May 4 12:26:10 CEST 2007


Gardner, Dean wrote:
>  
> So here it is....it might not be pretty (it seems a bit un-python like
> to me) but it works exactly as required. If anyone can give any tips for
> possible optimisation or refactor I would be delighted to hear from
> them. 
> 
> Thanks
> 
> 	  uid = self.item.Uid()
>         record=[]
>         logList=[]
>         displayList=[]
>         f = open(filename)
>         logTextFile="temp.txt"
>         """ searched through the changelog 'breaking' it up into
>             individual entries"""
>         try:
>             while 1:
>                 endofRecord=0
>                 l = f.next()
>                 if l.startswith("----"):
>                     record.append(l)
>                 l=f.next()
>                 while endofRecord==0:
>                     if "Reviewed: 000" not in l:
>                         record.append(l)
>                         l=f.next()
>                     else:
>                         logList.append(record)
>                         record=[]
>                         endofRecord=1
>         except StopIteration:
>             pass

I don't think you need endofRecord and the nested loops here. In fact I
think you could use a plain for loop here. AFAICT all you are doing is 
accumulating records with no special handling for anything except the 
end records. What about this:
record = []
for line in f:
   if "Reviewed: 000" in line:
     logList.append(record)
     record = []
   else:
     record.append(line)

>         """ searches to determine if we can find entries for
>             a particualr item"""
>         for record in logList:
>             currRec = record
>             for item in currRec:
>                 if uid in item:
>                     displayList.append(currRec)

The currRec variable is not needed, just use record directly.
If uid can only be in a specific line of the record you can test that 
directly, e.g.
for record in logList:
   if uid in record[1]:

>         """ creates a temporary file to write our find results to """
>         removeFile = os.path.normpath( os.path.join(os.getcwd(),
> logTextFile))
> 
>         # if the file exists, get rid of it before writing our new
> findings
>         if Shared.config.Exists(removeFile):
>             os.remove(removeFile)
>         recordLog = open(logTextFile,"a")
> 
>         for record in range(len(displayList)):
>             for item in displayList[record]:
>                 recordLog.write(item)

for record in displayList:
   recordLog.writelines(record)

>         recordLog.close()
>         #display our results
>         commandline = "start cmd /C " + logTextFile
>         os.system(commandline) 
> 

Kent


More information about the Tutor mailing list