Python_关键词替换输出

  • 发现一个好玩的东西,挺有意思;
# 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值;

@阴天-这几天说是有大暴雨

你可能感兴趣的:(Python_关键词替换输出)