-1

I am trying to see if a string I have is similar to any of the strings in a dictionary in python. When I am looking for exact matches, I can do this:

stringList = []
if (myString in stringList):
    #do something

Looking for similar matches using Python Levenshtein is the best I can come up with (I'm sure with some errors).

stringList = []
for i in range(len(stringList)):
    if distance(myString, stringList[i]) < 2:
        #do something
    else:
        #do something else

Is there a better way? Thanks.

The Nightman
  • 5,609
  • 13
  • 41
  • 74

3 Answers3

2

From https://stackoverflow.com/a/10018734/4941367

Use the difflib module.

difflib.get_close_matches(myString, myList)
Community
  • 1
  • 1
Jeremy
  • 818
  • 6
  • 19
2

it's more pythonic like this :

stringList = []
for item in stringList:
    if distance(myString, item) < 2:
        #do something
    else:
        #do something else

best regard

Emmanuel DUMAS
  • 680
  • 10
  • 25
1

If you don't care what string is close enough, you can use the min function:

if min(distance(x, myString) for x in stringList) < 2:
    # do something
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175