Quick compare string to list

Emile van Sebille emile at fenx.com
Wed Sep 30 21:06:14 CEST 2009


On 9/30/2009 11:36 AM Scooter said...
> I'm reading in a text file, and for each line in the file, I'm looking
> for the existence of phrases from a list. The list contains approx.
> 120 items currently but will most likely grow. This procedure itself
> is not the main function of my program and only grew out of the need
> to reformat certain phrases I'm finding in a file before re-outputting
> it. But as I suspected, this searching of the lists slows the whole
> process way way down. Was looking for ideas of a better way to do
> this.
> 
> I basically have
> 
> mylist=[]
> ...
> code that reads in the flat file into string 'flatfileString'
> ...
> for listitem in mylist:
>     if flatfileString.count(listitem):
>         ...whatever...I found it.
> 

Whatever you do next to reformat those certain phrases will require a 
second scan which doubles the time involved, and as you don't save the 
count anyway, if mylist were exchange couplets you could use replace 
directly.  Something like:

mylist = [('Chevy','Chevrolet'),
           ('GM','General Motors'),
           (... etc... )
          ]

for wrong,right in mylist:
     flatfileString=flatfileString.replace(wrong,right)


Flavor to taste,

Emile




More information about the Python-list mailing list