- 發(fā)現(xiàn)一個好玩的東西榛鼎,挺有意思咳榜;
# coding=utf-8
#!/usr/bin/python
import re
import six
class Xlator(dict):
def _make_regex(self):
return re.compile("|".join(map(re.escape, six.iterkeys(self))))
def __call__(self, match):
return self[match.group(0)]
def xlat(self, text):
return self._make_regex().sub(self, text)
text = "Larry Wall is the creator of Perl"
adict = {
"Larry Wall": "Guido van Rossum",
"creator": "Benevolent Dictator for Life",
"Perl": "Python",
}
xlat = Xlator(adict)
print xlat.xlat(text)
- 輸出
Guido van Rossum is the Benevolent Dictator for Life of Python
- 機制:去字典中便利關鍵字是否存在酥诽,如果有淮逻,則替換成value值琼懊;
@陰天-這幾天說是有大暴雨