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)
python按照词典中的单词对一一替换
最新推荐文章于 2024-06-23 09:38:44 发布