help please

Steven Bethard steven.bethard at gmail.com
Sat Feb 12 19:40:17 EST 2005


gargonx at gmail.com wrote:
> t2=""
> 
> def Proc(text): # "text" is some random text or use OrigText
>     for word in text:
>         for letter in word:
>             if letter in std.keys():
>                 letter=std[letter]
>                 t2=t2+letter  # the problem is referene to this
>             elif letter in ext.keys():
>                 letter=ext[letter]
>                 t2=t2+letter
>             elif letter in punc.keys():
>                 letter=punc[letter]
>                 t2=t2+letter

As written, t2 is a global because of the statement at the top:

t2=""

Inside Proc, the statement:

                  t2=t2+letter  # the problem is referene to this

declares t2 as local to the function.  (Assignment to a name inside a 
function declares that name as local to the function.)  You could use 
the global keyword, but a better approach would be something like:

replacements = std.items() + ext.items() + punc.items()

def proc(text):
     result = []
     for word in text:
         for k, v in replacements:
             word = word.replace(k, v)
         result.append(word)
     return ''.join(result)

Now, instead of using a global 't2', I simply create a string and return 
it.  Note that I've also replaced your inefficient string addition with 
the more efficient list-append and list-join.

Steve



More information about the Python-list mailing list