/WordSub.py

https://github.com/yaleimeng/py3Aiml_Chinese · Python · 68 lines · 62 code · 0 blank · 6 comment · 0 complexity · 97ab90201a5c31d7fa4b8cf61838f136 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. """这个模块实现了WordSub类,仿照“Python Cookbook”3.14中的配方(“在单一通道中替换多个模式”)。( by Xavier Defrang).
  3. 使用说明:
  4. 像字典一样使用这个类 添加 before/after 配对:
  5. > subber = TextSub()
  6. > subber["before"] = "after"
  7. > subber["begin"] = "end"
  8. 使用sub()方法执行替换
  9. > print subber.sub("before we begin")
  10. after we end
  11. 所有的匹配都是智能的不区分大小写
  12. > print subber.sub("Before we BEGIN")
  13. After we END
  14. 之前的单词必须是完整的单词 - 没有前缀以下示例说明了这一点
  15. > subber["he"] = "she"
  16. > print subber.sub("he says he'd like to help her")
  17. she says she'd like to help her
  18. 请注意 "he" "he'd" 被替换了, "help" "her" 并没有被替换"""
  19. from __future__ import print_function
  20. import re
  21. import string
  22. try:
  23. from ConfigParser import ConfigParser
  24. except ImportError:
  25. from configparser import ConfigParser
  26. class WordSub(dict):
  27. """多合一的多字符串替换类。."""
  28. def _wordToRegex(self, word):
  29. """将一个单词转换为与该单词匹配的正则表达式对象。"""
  30. if word != "" and word[0].isalpha() and word[-1].isalpha():
  31. return "\\b%s\\b" % re.escape(word)
  32. else:
  33. return r"\b%s\b" % re.escape(word)
  34. def _update_regex(self):
  35. """基于当前字典的键 来构建 re 对象。 """
  36. self._regex = re.compile("|".join(map(self._wordToRegex, self.keys())))
  37. self._regexIsDirty = False
  38. def __init__(self, defaults = {}):
  39. """初始化对象, 用默认字典中的条目填充它。 """
  40. self._regex = None
  41. self._regexIsDirty = True
  42. for k,v in defaults.items():
  43. self[k] = v
  44. def __call__(self, match):
  45. """ 为每个正则表达式匹配触发 Handler。"""
  46. return self[match.group(0)]
  47. def __setitem__(self, i, y):
  48. self._regexIsDirty = True
  49. # 对于用户添加的每个条目我们实际添加三个入口
  50. super(type(self),self).__setitem__(i.lower(),y.lower()) # key = value
  51. super(type(self),self).__setitem__(string.capwords(i), string.capwords(y)) # Key = Value
  52. super(type(self),self).__setitem__(i.upper(), y.upper()) # KEY = VALUE
  53. def sub(self, text):
  54. """翻译文本,返回修改后的文本。"""
  55. if self._regexIsDirty:
  56. self._update_regex()
  57. return self._regex.sub(self, text)