Add a function to guess the closest word for a miss input

This commit is contained in:
nemunaire 2015-09-08 20:14:27 +02:00
commit 9686f36522
2 changed files with 15 additions and 1 deletions

View file

@ -57,3 +57,13 @@ def word_distance(str1, str2):
)
return d[len(str1)][len(str2)]
def guess(pattern, expect):
if len(expect):
se = sorted([(e, word_distance(pattern, e)) for e in expect], key=lambda x: x[1])
_, m = se[0]
for e, wd in se:
if wd > m or wd > 1 + len(pattern) / 4:
break
yield e

View file

@ -1,6 +1,6 @@
import unittest
from nemubot.tools.human import size, word_distance
from nemubot.tools.human import guess, size, word_distance
class TestHuman(unittest.TestCase):
@ -31,6 +31,10 @@ class TestHuman(unittest.TestCase):
self.assertEqual(word_distance("long", "short"), 4)
self.assertEqual(word_distance("long", "short"), word_distance("short", "long"))
def test_guess(self):
self.assertListEqual([g for g in guess("drunk", ["eat", "drink"])], ["drink"])
self.assertListEqual([g for g in guess("drunk", ["long", "short"])], [])
if __name__ == '__main__':
unittest.main()