python:比较两个字符串

时间:2010-08-23 20:29:53

标签: python string

我想知道是否有一个库会告诉我两个字符串有多相似

我不是在寻找具体的东西,但在这种情况下:

a = 'alex is a buff dude'
b = 'a;exx is a buff dud'

我们可以说ba的相似度约为90%。

是否有可以执行此操作的库?

4 个答案:

答案 0 :(得分:18)

import difflib

>>> a = 'alex is a buff dude'
>>> b = 'a;exx is a buff dud'
>>> difflib.SequenceMatcher(None, a, b).ratio()

0.89473684210526316

答案 1 :(得分:6)

查找用于比较字符串的Levenshtein算法。这是通过谷歌发现的随机实现:http://hetland.org/coding/python/levenshtein.py

答案 2 :(得分:6)

http://en.wikipedia.org/wiki/Levenshtein_distance

pypi上有一些库,但要注意这很贵,特别是对于较长的字符串。

您可能还想查看python的difflib:http://docs.python.org/library/difflib.html

答案 3 :(得分:1)

其他方式是使用最长的公共子串。这里是Daniweb中我的lcs实现的实现(这也在difflib中定义)

这是一个简单的长度版本,列表作为数据结构:

def longest_common_sequence(a,b):

    n1=len(a)
    n2=len(b)

    previous=[]
    for i in range(n2):
        previous.append(0)

    over = 0
    for ch1 in a:
        left = corner = 0
        for ch2 in b:
            over = previous.pop(0)
            if ch1 == ch2:
                this = corner + 1
            else:
                this = over if over >= left else left
            previous.append(this)
            left, corner = this, over
    return 200.0*previous.pop()/(n1+n2)

这是我的第二个带有deque数据结构的version which actualy gives the common string(也是示例数据用例):

from collections import deque

a = 'alex is a buff dude'
b = 'a;exx is a buff dud'

def lcs_tuple(a,b):

    n1=len(a)
    n2=len(b)

    previous=deque()
    for i in range(n2):
        previous.append((0,''))

    over = (0,'')
    for i in range(n1):
        left = corner = (0,'')
        for j in range(n2):
            over = previous.popleft()
            if a[i] == b[j]:
                this = corner[0] + 1, corner[1]+a[i]
            else:
                this = max(over,left)
            previous.append(this)
            left, corner = this, over
    return 200.0*this[0]/(n1+n2),this[1]
print lcs_tuple(a,b)

""" Output:
(89.47368421052632, 'aex is a buff dud')
"""