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.

88 lines
3.4 KiB

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