I want to create a instance of class Token that takes a string as an argument, this class should also have method punc that tokenize the string according to the method.instance. or raise an not implement error with a message. Problem is that I am new to OOP, class, attribute. I don’t know how to pass the string as an argument and method will work on the string according to the string passed in class instance.
a = Token("a-z")
a.punc("Are you sure?")
output I am looking for "a-z"
['Are','you','sure']
a = Token("c")
a.punc("Are you sure?")
output I am looking for "c"
['Are','you','sure?']
class Token:
def __init__(self,string):
self.az = "a-z"
self.c = "c"
self.string=string
if "a-z" in string:
string = string.split('?')
if "c" in string:
string = string.split()
def punc (self,string):
return self.string
output I get a-z which is not the right one. I know the coding is wrong, since I really not sure how to pass string as an argument. Any help will be appreciated :)
Advertisement
Answer
Are you looking for something like this?
import re
class Token:
def __init__(self, az):
# we only initialize az in here
# which can hold only a-z or c
self.az = az
# string is empty
self.string=''
def punc(self, string):
# now we check if the az was 'a-z' or 'c'
if self.az=='a-z':
# we then remove all non alpha numeric char
# and split
self.string = re.sub(r'[^A-Za-z0-9 ]+', '', string).split()
if self.az=='c':
# or just split
self.string = string.split()
return self.string
a = Token("a-z")
print(a.punc("Are you sure?"))
b = Token("c")
print(b.punc("Are you sure?"))
result:
['Are', 'you', 'sure'] ['Are', 'you', 'sure?']