Skip to content

Commit 0dd713c

Browse files
committed
replace word
1 parent bbdd308 commit 0dd713c

1 file changed

Lines changed: 21 additions & 12 deletions

File tree

newcodes/answers/q70.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,26 @@
11
#!/usr/bin/env python
22
# coding=utf-8
33

4-
class Keeper:
5-
def __init__(self, keep):
6-
self.keep = keep
7-
def __getitem__(self, s):
8-
if s not in self.keep:
9-
return None
10-
return s
11-
def __call__(self, s):
12-
return s.translate(self)
4+
import re
5+
6+
class make_xlat:
7+
def __init__(self, *args, **kwargs):
8+
self.adict = dict(*args, **kwargs)
9+
self.rx = self.make_rx()
10+
11+
def make_rx(self):
12+
return re.compile('|'.join(map(re.escape, self.adict)))
13+
14+
def one_xlat(self, match):
15+
return self.adict[match.group(0)]
16+
17+
def __call__(self, text):
18+
return self.rx.sub(self.one_xlat, text)
1319

1420
if __name__ == "__main__":
15-
mf = Keeper
16-
cang = mf('canglaoshi')
17-
print(cang("what is your name? my name is laoshicang"))
21+
text = "PHP is the best language"
22+
adict = {"PHP": "Canglaoshi", "language":"teacher",}
23+
t = make_xlat(adict)
24+
print(text)
25+
print("--->")
26+
print(t(text))

0 commit comments

Comments
 (0)