A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
3.6 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from re import sub, UNICODE
  23. __all__ = ["EMPTY", "EMPTY_INTERSECTION", "MarkovChain",
  24. "MarkovChainIntersection"]
  25. class MarkovChain:
  26. """Implements a basic ngram Markov chain of words."""
  27. START = -1
  28. END = -2
  29. degree = 5 # 2 for bigrams, 3 for trigrams, etc.
  30. def __init__(self, text):
  31. self.text = text
  32. self.chain = self._build()
  33. self.size = self._get_size()
  34. def _build(self):
  35. """Build and return the Markov chain from the input text."""
  36. padding = self.degree - 1
  37. words = sub(r"[^\w\s-]", "", self.text.lower(), flags=UNICODE).split()
  38. words = ([self.START] * padding) + words + ([self.END] * padding)
  39. chain = {}
  40. for i in range(len(words) - self.degree + 1):
  41. phrase = tuple(words[i:i+self.degree])
  42. if phrase in chain:
  43. chain[phrase] += 1
  44. else:
  45. chain[phrase] = 1
  46. return chain
  47. def _get_size(self):
  48. """Return the size of the Markov chain: the total number of nodes."""
  49. return sum(self.chain.values())
  50. def __repr__(self):
  51. """Return the canonical string representation of the MarkovChain."""
  52. return "MarkovChain(text={0!r})".format(self.text)
  53. def __str__(self):
  54. """Return a nice string representation of the MarkovChain."""
  55. return "<MarkovChain of size {0}>".format(self.size)
  56. class MarkovChainIntersection(MarkovChain):
  57. """Implements the intersection of two chains (i.e., their shared nodes)."""
  58. def __init__(self, mc1, mc2):
  59. self.mc1, self.mc2 = mc1, mc2
  60. self.chain = self._build()
  61. self.size = self._get_size()
  62. def _build(self):
  63. """Build and return the Markov chain from the input chains."""
  64. c1 = self.mc1.chain
  65. c2 = self.mc2.chain
  66. chain = {}
  67. for phrase in c1:
  68. if phrase in c2:
  69. chain[phrase] = min(c1[phrase], c2[phrase])
  70. return chain
  71. def __repr__(self):
  72. """Return the canonical string representation of the intersection."""
  73. res = "MarkovChainIntersection(mc1={0!r}, mc2={1!r})"
  74. return res.format(self.mc1, self.mc2)
  75. def __str__(self):
  76. """Return a nice string representation of the intersection."""
  77. res = "<MarkovChainIntersection of size {0} ({1} ^ {2})>"
  78. return res.format(self.size, self.mc1, self.mc2)
  79. EMPTY = MarkovChain("")
  80. EMPTY_INTERSECTION = MarkovChainIntersection(EMPTY, EMPTY)