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.

95 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 collections import defaultdict
  23. from re import sub, UNICODE
  24. __all__ = ["EMPTY", "EMPTY_INTERSECTION", "MarkovChain",
  25. "MarkovChainIntersection"]
  26. class MarkovChain(object):
  27. """Implements a basic ngram Markov chain of words."""
  28. START = -1
  29. END = -2
  30. degree = 3 # 2 for bigrams, 3 for trigrams, etc.
  31. def __init__(self, text):
  32. self.text = text
  33. self.chain = defaultdict(lambda: defaultdict(lambda: 0))
  34. words = sub("[^\w\s-]", "", text.lower(), flags=UNICODE).split()
  35. padding = self.degree - 1
  36. words = ([self.START] * padding) + words + ([self.END] * padding)
  37. for i in range(len(words) - self.degree + 1):
  38. last = i + self.degree - 1
  39. self.chain[tuple(words[i:last])][words[last]] += 1
  40. self.size = self._get_size()
  41. def _get_size(self):
  42. """Return the size of the Markov chain: the total number of nodes."""
  43. size = 0
  44. for node in self.chain.itervalues():
  45. for hits in node.itervalues():
  46. size += hits
  47. return size
  48. def __repr__(self):
  49. """Return the canonical string representation of the MarkovChain."""
  50. return "MarkovChain(text={0!r})".format(self.text)
  51. def __str__(self):
  52. """Return a nice string representation of the MarkovChain."""
  53. return "<MarkovChain of size {0}>".format(self.size)
  54. class MarkovChainIntersection(MarkovChain):
  55. """Implements the intersection of two chains (i.e., their shared nodes)."""
  56. def __init__(self, mc1, mc2):
  57. self.chain = defaultdict(lambda: defaultdict(lambda: 0))
  58. self.mc1, self.mc2 = mc1, mc2
  59. c1 = mc1.chain
  60. c2 = mc2.chain
  61. for word, nodes1 in c1.iteritems():
  62. if word in c2:
  63. nodes2 = c2[word]
  64. for node, count1 in nodes1.iteritems():
  65. if node in nodes2:
  66. count2 = nodes2[node]
  67. self.chain[word][node] = min(count1, count2)
  68. self.size = self._get_size()
  69. def __repr__(self):
  70. """Return the canonical string representation of the intersection."""
  71. res = "MarkovChainIntersection(mc1={0!r}, mc2={1!r})"
  72. return res.format(self.mc1, self.mc2)
  73. def __str__(self):
  74. """Return a nice string representation of the intersection."""
  75. res = "<MarkovChainIntersection of size {0} ({1} ^ {2})>"
  76. return res.format(self.size, self.mc1, self.mc2)
  77. EMPTY = MarkovChain("")
  78. EMPTY_INTERSECTION = MarkovChainIntersection(EMPTY, EMPTY)