I have a small 30 line text file with two similar words on each line. I need to calculate the levenshtein distance between the two words on each line. I also need to use a memoize function while calculating the distance. I am pretty new to Python and algorithms in general, so this is proving to be quite difficult of me. I have the file open and being read, but I cannot figure out how to assign each of the two words to variables 'a' & 'b' to calculate the distance.
Here is my current script that ONLY prints the document as of right now:
txt_file = open('wordfile.txt', 'r')
def memoize(f):
cache = {}
def wrapper(*args, **kwargs):
try:
return cache[args]
except KeyError:
result = f(*args, **kwargs)
cache[args] = result
return result
return wrapper
@memoize
def lev(a,b):
if len(a) > len(b):
a,b = b,a
b,a = a,b
current = range(a+1)
for i in range(1,b+1):
previous, current = current, [i]+[0]*n
for j in range(1,a+1):
add, delete = previous[j]+1, current[j-1]+1
change = previous[j-1]
if a[j-1] != b[i-1]:
change = change + 1
current[j] = min(add, delete, change)
return current[b]
if __name__=="__main__":
with txt_file as f:
for line in f:
print line
Here are a few words from the text file so you all get an idea:
archtypes, archetypes
propietary, proprietary
recogize, recognize
exludes, excludes
tornadoe, tornado
happenned, happened
vacinity, vicinity
HERE IS AN UPDATED VERSION OF THE SCRIPT, STILL NOT FUNCTIONAL BUT BETTER:
class memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args]
except KeyError:
self.memoized[args] = self.function(*args)
return self.memoized[args]
@memoize
def lev(a,b):
n, m = len(a), len(b)
if n > m:
a, b = b, a
n, m = m, n
current = range(n + 1)
for i in range(1, m + 1):
previous, current = current, [i] + [0] * n
for j in range(1, n + 1):
add, delete = previous[j] + 1, current[j - 1] + 1
change = previous[j - 1]
if a[j - 1] != b[i - 1]:
change = change + 1
current[j] = min(add, delete, change)
return current[n]
if __name__=="__main__":
for pair in open("wordfile.txt", "r"):
a,b = pair.split()
lev(a, b)