473,406 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

help please

would anyone like to help to fugure out this problem i'm having here's
a portion of my code:

"""
I have three dictionaries along with this(you can probally spot what
they are), but just in case here are some testers:
"""
std = {
"b":"bo"
}

ext = {
"aa":"i"
}

punc = {
",":"!"
}
"""
when i run this i get :

UnboundLocalError: local variable 't2' referenced before assignment

"""

OrigText="ba, baa bo."

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

can anyone figure out why t2 is not being used properly?

Jul 18 '05 #1
21 1345
ga*****@gmail.com wrote:
UnboundLocalError: local variable 't2' referenced before assignment
...
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

can anyone figure out why t2 is not being used properly?


The problem is that you're not making it clear to Python that you want
the t2 mentioned in Proc to reference the global t2, rather than a
local. It's concluding the latter, whereas you mean the former. You
can probably see that as a local, t2 is indeed referenced before it's
assigned (t2 = t2 + letter). The fix is to declare t2 global at the top
of Proc:

def Proc(text):
global t2
...

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
I am become death, the destroyer of worlds.
-- J. Robert Oppenheimer (quoting Hindu legend)
Jul 18 '05 #2
ga*****@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
Jul 18 '05 #3
Erik Max Francis wrote:
ga*****@gmail.com wrote:
UnboundLocalError: local variable 't2' referenced before assignment


...
t2=""

def Proc(text): # "text" is some random text or use OrigText
...


The fix is to declare t2 global at the top of Proc:

def Proc(text):
global t2
...


But please don't. The global declaration is a wart of Python, and in
most cases, your code will be much cleaner if you avoid it. Certainly
in this case, making t2 a local of the function is much more sensible.
If you stick with your current implementation (which I advise against),
you should write it something like:

def proc(text):
t2 = ""
...
# your Proc code here
...
return t2

Steve
Jul 18 '05 #4
add just below the procedure declaration 'global t2' as you're
referring to a global variable ...

Jul 18 '05 #5
This works much better, aside from the fact that it does'nt work for
the std dictionary. the letters used from here stay the same. that
dictionary looks like this:

std = {
"A":"Z",
"Z":"A",
"B":"Y",
"Y":"B",
"C":"X",
"X":"C",
"E":"V",
"V":"E",
"H":"S",
"S":"H",
"M":"N",
"N":"M"
}

what could be causing this?

i did figure out that if you reverse the k,v you are able to get it but
that doesn't turn up the results i need

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

Jul 18 '05 #6
Thanks that works very well

Jul 18 '05 #7
wi******@hotmail.com wrote:
add just below the procedure declaration 'global t2' as you're
referring to a global variable ...


More specifically, *modifying* it. Just referring to it
doesn't require a "global" declaration...

-Peter
Jul 18 '05 #8
gargonx wrote:
This works much better, aside from the fact that it does'nt work for
the std dictionary. the letters used from here stay the same. that
dictionary looks like this:

std = {
"A":"Z",
"Z":"A",
"B":"Y",
"Y":"B",
"C":"X",
"X":"C",
"E":"V",
"V":"E",
"H":"S",
"S":"H",
"M":"N",
"N":"M"
}

what could be causing this?

i did figure out that if you reverse the k,v you are able to get it but
that doesn't turn up the results i need

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

The problem is that if you run all the replacements in std, you first
translate As to Zs and then Zs to As. If you want to do each character
only once, you should probably write this as:

py> std = {
.... "A":"Z",
.... "Z":"A",
.... "B":"Y",
.... "Y":"B",
.... "C":"X",
.... "X":"C",
.... "E":"V",
.... "V":"E",
.... "H":"S",
.... "S":"H",
.... "M":"N",
.... "N":"M"}
py> ext = {"aa":"i"}
py> punc = {",":"!"}
py> replacements = {}
py> replacements.update(punc)
py> replacements.update(ext)
py> replacements.update(std)
py> def proc(text):
.... result = []
.... for char in text:
.... result.append(replacements.get(char, char))
.... return ''.join(result)
....
py> proc('ABCDEFG')
'ZYXDVFG'

Or alternatively:

py> def proc(text):
.... return ''.join([replacements.get(c, c) for c in text])
....
py> proc('ABCDEFG')
'ZYXDVFG'

Note however, that this won't work for multi-character strings like you
had in 'ext' in your original example:

py> proc('ABCaaEFG')
'ZYXaaVFG'

But neither would your original code. Are the items in std always a
single character? Does ext always translate two characters to one?
Could you give us some more info on the task here?

Steve
Jul 18 '05 #9
yes the items in std are always single to single, and ext single to
double. basicly the ext are refernce to the std itmes. the second
character in ext is a number depending on how far it is from the item
in std. this is just a simple encoding program.

Jul 18 '05 #10
gargonx wrote:
yes the items in std are always single to single, and ext single to
double. basicly the ext are refernce to the std itmes. the second
character in ext is a number depending on how far it is from the item
in std. this is just a simple encoding program.


If your keys are always single characters (as this description seems to
suggest) then the last code I posted should do what you want. Repeated
here for your enjoyment:

# merge mappings:
# std has highest precedence, then ext, then punc
replacements = {}
replacements.update(punc)
replacements.update(ext)
replacements.update(std)

# define encoding procedure
def proc(text):
# replace each character with its replacement
# or leave character unchanged if not in the mapping
return ''.join([replacements.get(c, c) for c in text])

Steve
Jul 18 '05 #11
Well that seems to work like a champion, but my prob then would be; how
do i get the double character values of ext to turn back to the single
character keys. The reversed (decode if you will). Thanks a lot Steve
this has been a great learning!

Jul 18 '05 #12
gargonx wrote:
Well that seems to work like a champion, but my prob then would be; how
do i get the double character values of ext to turn back to the single
character keys. The reversed (decode if you will).


It's unclear what you want to do here. If you have say:

ext = dict(aa='A', ab='B', bb='C')

then how should 'aaabb' be decoded? Some possibilities:

'ABb'
'AaC'
'aAC'

Steve
Jul 18 '05 #13
let's take the word "dogs"

ext = dict("D":"V1", "O":"M1", "G":"S1")
std = dict("S":"H")

encode("DOGS") # proc()
we'll get: "V1M1S1H"

let's say i want to do just the opposite
word: "V1M1S1H"
decode("V1M1S1H")
#how do i decode "V1" to "D", how do i keep the "V1" together?
and get: "DOGS"

#everything gets changed to uppercase

Jul 18 '05 #14
gargonx wrote:
let's take the word "dogs"

ext = dict("D":"V1", "O":"M1", "G":"S1")
std = dict("S":"H")

encode("DOGS") # proc()
we'll get: "V1M1S1H"

let's say i want to do just the opposite
word: "V1M1S1H"
decode("V1M1S1H")
#how do i decode "V1" to "D", how do i keep the "V1" together?
and get: "DOGS"


If you can make some assumptions about the right-hand sides of your
dicts, you can probably tokenize your string with a simple regular
expression:

py> import re
py> charmatcher = re.compile(r'[A-Z][\d]?')
py>
py> ext = dict(D="V1", O="M1", G="S1")
py> std = dict(S="H")
py>
py> decode_replacements = {}
py> decode_replacements.update([(std[key], key) for key in std])
py> decode_replacements.update([(ext[key], key) for key in ext])
py>
py> def decode(text):
.... return ''.join([decode_replacements.get(c, c)
.... for c in charmatcher.findall(text)])
....
py>
py> decode("V1M1S1H")
'DOGS'

So, instead of using
for c in text
I use
for c im charmatcher.findall(text)
That gives me the correct tokenization, and i can just use the inverted
dicts to map it back. Note however that I've written the regular
expression to depend on the fact that the values in std and ext are
either single uppercase characters or single uppercase characters
followed by a single digit.

Steve
Jul 18 '05 #15
I think there's a problem with the code:

py> decode_replacements.update([(std[key], key) for key in std])
py> decode_replacements.update([(ext[key], key) for key in ext])

when i run this i get an error:
AttributeError: keys

I can't get that figured out

Jul 18 '05 #16
gargonx wrote:
I think there's a problem with the code:

py> decode_replacements.update([(std[key], key) for key in std])
py> decode_replacements.update([(ext[key], key) for key in ext])

when i run this i get an error:
AttributeError: keys

I can't get that figured out


Can you show the part of your code in which you do this? As you can see
from the interactive Python session I posted, I didn't get an
AttributeError...

STeVe
Jul 18 '05 #17
Even if i put it in exactly the way you did:
import re
charmatcher = re.compile(r' [A-Z] [\d]?')

ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")

decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std])

Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys

Jul 18 '05 #18
gargonx wrote:
Even if i put it in exactly the way you did:
import re
charmatcher = re.compile(r' [A-Z] [\d]?')

ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")

decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std])


Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys


What version of Python are you using? Here's what I get:

PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)]
on win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
py>
py> import re
py> charmatcher = re.compile(r' [A-Z] [\d]?')
py>
py> ext = dict(D="V1", O="M1", G="S1")
py> std = dict(S="H")
py>
py> decode_replacements = {}
py> decode_replacements.update([(std[key], key) for key in std])

As you can see, I'm using Python 2.4. I'm guessing you're using an
earlier version. I just checked the docs for dict.update:

"update() accepts either another mapping object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If keyword
arguments are specified, the mapping is then is updated with those
key/value pairs: "d.update(red=1, blue=2)". Changed in version 2.4:
Allowed the argument to be an iterable of key/value pairs and allowed
keyword arguments."

So dict.update() only accepts a list of key/value pairs as of 2.4 I
guess. Try:

py> decode_replacements.update(dict([(std[key], key) for key in std]))

I believe that, unlike dict.update, the dict constructor allowed a list
of key/value pairs previous to Python 2.4. If that doesn't work either,
you can do the more verbose version:

py> for key in std:
.... decode_replacements[std[key]] = key
....

STeVe
Jul 18 '05 #19
On 20 Feb 2005 20:12:50 -0800, "gargonx" <ga*****@gmail.com> declaimed
the following in comp.lang.python:
decode_replacements.update([(std[key], key) for key in std]) Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys
Did you read the reference manual?

.update() wants a DICTIONARY argument, you are creating a list
of tuples. So of course there are no keys available for update...

Try:

decode_replacements.update(dict([(std[key], key) for key in std]))
std = {"S":"H", "B":"v"}
decode_replacements = {}
print std {'S': 'H', 'B': 'v'} decode_replacements.update(dict([(std[key], key) for key in std])) Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: keys decode_replacements.update(dict([(std[key], key) for key in std]))
print decode_replacements {'H': 'S', 'v': 'B'}

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 18 '05 #20
Dennis Lee Bieber wrote:
On 20 Feb 2005 20:12:50 -0800, "gargonx" <ga*****@gmail.com> declaimed
the following in comp.lang.python:
>decode_replacements.update([(std[key], key) for key in std])


Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys


Did you read the reference manual?


Yes, actually. But I generally check only the reference manual for the
current version of Python:

http://docs.python.org/lib/typesmapping.html

which does support sequence arguments for dict.update. As noted there,
of course, this support was added for Python 2.4.

STeVe
Jul 18 '05 #21

"gargonx" <ga*****@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Even if i put it in exactly the way you did:
import re
charmatcher = re.compile(r' [A-Z] [\d]?')

ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")

decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std]) Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys

Works with 2.4, but not with 2.3.4:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import re
charmatcher = re.compile(r' [A-Z] [\d]?')

ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")

decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std])

print decode_replacements {'H': 'S'}

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information. import re
charmatcher = re.compile(r' [A-Z] [\d]?')

ext = dict(D="V1", O="M1", G="S1")
std = dict(S="H")

decode_replacements ={}
decode_replacements.update([(std[key], key) for key in std]) Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: keys
print decode_replacements

{}


Jul 18 '05 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: laurie | last post by:
Hi all, I'm trying to help out a friend who has inherited a client with a PHP shopping cart application. Neither of us know PHP, but I've been muddling my way through, trying to get these old...
1
by: the_proud_family | last post by:
HELP ME PLEASE!! my email is the_proud_family@yahoo.com I can't get the ball to go up right side and then I need it to turn around and keep turning until velocity=0 I have been at it for the ...
0
by: Kurt Watson | last post by:
I’m having a different kind of problem with Hotmail when I sign in it says, "Web Browser Software Limitations Your Current Software Will Limit Your Ability to Use Hotmail You are using a web...
12
by: Christo | last post by:
borland c++ 5.01 character constant must be one or two characters long get this when compiling my first c++ program can anyone out there help? it is highlighting this line as the problem ...
7
by: x muzuo | last post by:
Hi guys, I have got a prob of javascript form validation which just doesnt work with my ASP code. Can any one help me out please. Here is the code: {////<<head> <title>IIBO Submit Page</title>...
5
by: Craig Keightley | last post by:
Please help, i have attached my page which worksin IE but i cannnot get the drop down menu to fucntion in firefox. Any one have any ideas why? Many Thanks Craig ...
17
by: JT | last post by:
Help me the following C++ question: Write a program to help a local bookshop automate its billing system. The program should do the following: (a)Let the user enter the ISBN, the system will...
7
by: tyler_durden | last post by:
thanks a lot for all your help..I'm really appreciated... with all the help I've been getting in forums I've been able to continue my program and it's almost done, but I'm having a big problem that...
23
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application...
2
by: =?Utf-8?B?U2NvdHRSYWREZXY=?= | last post by:
I'm creating a doc project for my c# program. I've done this before but this time sonething is wrong. I build my doc project and is succeeds but when I open the help file, there is no documentation...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.