开发者

a slightly different string equivalence function in python

I have a number of strings that won't match exactly but should be considered equivalent. For example 'Bob' and 'Robert' or 'WWF' and 'World Wrestling Federation'.

To implement the equivalence function, I was going to put all the equivalent strings into tuples and then all the tuples into a list. Then for each input string pair, check if they both exist inside the same tuple and return true if so. Can anyone suggest a more elegant way to do this?

Thanks, Richard

EDIT: To clarif开发者_如何学Pythony, the function could receive any two of ('Bob','Robbie','Robert','Roberto') and should return true.


If your list of equivalence tuples is EQUIVALENCES, you can create a dictionary mapping each string to its equivalences:

word_equivs = {}

for equiv in EQUIVALENCES:
    for word in equiv:
        word_equivs[word] = equiv

Then you can check if two strings are equivalent by seeing if they map to the same equivalence:

def equivalent(s1, s2):
    e1 = word_equivs.get(s1) 
    e2 = word_equivs.get(s2)
    if e1 and e2:
        return e1 == e2
    else:
        return s1 == s2


I would suggest using a dictionary from string to int. Then for every set of equivalent strings increment a counter variable counter may be using a

counter  = 0
d = defaultdict(int)
d["WWF"] = d["World Wrestling Federation"] = counter++;
d["Bob"]=d["Marley"]=counter++

And when you want to find out equivalence just do

if( d[s1]==d[s2] )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜