I apologize for the newbie question, but this is my first time working with classes. The class I’m trying to create is intended to perform a regex find and replace on all keys and values within a dictionary. The specific find and replace is defined upon instantiation.
There are two issues that I have. The first issue is that each instance of the class needs to accept a new dictionary. I’m not clear on how to create a class that accepts a general dictionary which I can specify upon creating an instance.
The second issue is that the class I have simply isn’t working. I’m receiving the error message TypeError: expected string or buffer in the class line v = re.sub(self.find,self.replace,v).
There are three instances I want to create, one for each input dictionary: input_iter1, input_iter2, and input_iter3.
The following is the class:
class findreplace:
values = []
keys = []
def __init__(self, find, replace):
self.find = find
self.replace = replace
def value(self):
for k,v in input_iter1.items():
v = re.sub(self.find,self.replace,v)
findreplace.values.append(v)
def key(self):
for k,v in input_iter1.items():
k = re.sub(self.find,self.replace,k)
findreplace.keys.append(k)
The following are the instances:
values1 = findreplace('[)?:(]','')
values1.value()
values2 = findreplace(r'(,\s)(,\s)(\d{5})({e<=1})',r'\2\3')
values2.value()
keys1 = findreplace(r'(?<=^)(.+)(?=$)',r'(?:\1)')
keys1.key()
keys2 = findreplace(r'(?=$)',r'{e}')
keys2.key()
print values
print keys
If anyone has any insight on how I can workaround these two issues, I’d be grateful to hear them. Thanks!
First, Python 2 classes should start off this way:
Otherwise, you get an “old-style class”, which is some ancient crusty thing no one uses.
Also, class names in Python are typically written in
CamelCase.Second, do not use mutable values (like lists!) as class attributes, as you’re doing here with
keysandvalues. They’ll be shared across all instances of your class! It looks like you’re even aware of this, since you refer tofindreplace.keysdirectly, but it doesn’t make sense to store instance-specific values in a class attribute like that.But, most importantly: why is this a class at all? What does a
findreplacerepresent? It looks like this would be much clearer if it were just a single function.To answer your actual questions:
You pass in a dictionary just like you’re passing in
findandreplace. Add another argument to__init__, and pass another argument when you construct your class.Presumably, you’re getting the
TypeErrorbecause one of the values in your dictionary isn’t a string, and you can only perform regexes on strings.