Guest User

Untitled

a guest
Apr 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. import random, math, re, pickle
  2. class Markov:
  3. def __init__(self):
  4. self.dict = {}
  5. self.stripre = re.compile(r'\s+')
  6.  
  7. def add(self, text, weight=0):
  8. x = 1
  9. text = self.stripre.sub(' ', text).split(' ')
  10. for word in text:
  11. previous = text[x-1]
  12. try: word = text[x]
  13. except: word = None
  14.  
  15. try: self.dict[previous]
  16. except: self.dict[previous] = {}
  17.  
  18. try: self.dict[previous][word] += float(1 + weight)
  19. except: self.dict[previous][word] = float(1 + weight)
  20.  
  21. x = x + 1
  22. # {'bd': {'a': 1}, 'ca': {'b': 1}, 'ab': {'c': 2, 'd': 1}, 'da': {'b': 1}, 'bc': {'a': 1, None: 1}}
  23. return self.dict
  24.  
  25. def walk(self, seed):
  26. try: prob = self.dict[seed]
  27. except: prob = self.dict[random.choice(self.dict.keys())]
  28. self.weighted = []
  29. for key, value in prob.items():
  30. for x in range(int(value)):
  31. self.weighted.append(key)
  32. result = random.choice(self.weighted)
  33. return result
  34.  
  35. def sentance(self, length=10, seed='default', postimes=50):
  36. while seed == "default" or seed.endswith('.'): seed = random.choice(self.dict.keys())
  37. ending = random.choice(self.dict.keys())
  38. sentance = None
  39. for x in range(postimes):
  40. key = random.choice(self.dict.keys())
  41. if key.endswith('.'):
  42. ending = key
  43. break
  44.  
  45. if seed == None or seed == "": sentance = self.walk(seed)
  46. else: sentance = seed
  47. for x in range(length-2):
  48. s = self.walk(sentance.split(' ')[x])
  49. if s == None: break
  50. while s == sentance.split(' ')[x]: s = self.walk(sentance.split(' ')[x])
  51. sentance = sentance + ' ' + s
  52.  
  53.  
  54. sentance = sentance + ' ' + ending
  55. return sentance + "\n"
  56.  
  57. def respondTo(self, msg):
  58. return self.sentance(seed=random.choice(sorted(msg.split(' '), lambda x, y: len(y)-len(x))[:3]), length=random.choice(range(10,15)))
  59.  
  60. def save(self, filename):
  61. fh = open(filename, 'w')
  62. pickle.dump(self.dict, fh)
  63. fh.close()
  64.  
  65. def load(self, filename):
  66. try:
  67. fh = open(filename, 'r')
  68. self.dict = pickle.load(fh)
  69. fh.close()
  70. except:
  71. print "File not found. Not loaded. " + str(filename)
  72.  
  73. def test():
  74. m = Markov()
  75. m.add("dog cat dog cat dog chicken")
  76. cs = 0
  77. ds = 0
  78. ratios = []
  79. average = float(0)
  80. for i in range(500):
  81. for i in range(500):
  82. if m.walk("dog") == "cat":
  83. cs = cs + 1
  84. else:
  85. ds = ds + 1
  86. ratio = float(cs)/float(ds)
  87. ratios.append(ratio)
  88. print ratios
  89. for item in ratios:
  90. average = average + item
  91. average = average / float(len(ratios))
  92. print "------------------------------------\nIdeal: 2"
  93. print "Average: %f" % average
  94. print "Margin of error: %f%%" % (((2 - average)/2) * 100)
  95.  
  96. if __name__ == "__main__":
  97. test()
Add Comment
Please, Sign In to add comment