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.
JavaScript
x
12
12
1
a = Token("a-z")
2
a.punc("Are you sure?")
3
4
output I am looking for "a-z"
5
['Are','you','sure']
6
7
a = Token("c")
8
a.punc("Are you sure?")
9
10
output I am looking for "c"
11
['Are','you','sure?']
12
JavaScript
1
17
17
1
class Token:
2
3
def __init__(self,string):
4
self.az = "a-z"
5
self.c = "c"
6
self.string=string
7
8
if "a-z" in string:
9
string = string.split('?')
10
11
if "c" in string:
12
string = string.split()
13
14
15
def punc (self,string):
16
return self.string
17
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?
JavaScript
1
29
29
1
import re
2
class Token:
3
4
def __init__(self, az):
5
# we only initialize az in here
6
# which can hold only a-z or c
7
self.az = az
8
# string is empty
9
self.string=''
10
11
def punc(self, string):
12
# now we check if the az was 'a-z' or 'c'
13
if self.az=='a-z':
14
# we then remove all non alpha numeric char
15
# and split
16
self.string = re.sub(r'[^A-Za-z0-9 ]+', '', string).split()
17
18
if self.az=='c':
19
# or just split
20
self.string = string.split()
21
return self.string
22
23
24
a = Token("a-z")
25
print(a.punc("Are you sure?"))
26
27
b = Token("c")
28
print(b.punc("Are you sure?"))
29
result:
JavaScript
1
3
1
['Are', 'you', 'sure']
2
['Are', 'you', 'sure?']
3