2015-01-12 112 views
0

如:如何计算python中的字符串中的字符匹配?

String 1: Can We Live (feat. Cece Rogers) [Joke Instrumental Mix] 
String 2: Can We Live (feat. Cece Rogers) Joke Instrumental Mix 

Match count = 53 

读过这个:Character match count between strings in perl

要做到这一点pythonically。

+1

你到目前为止试过的东西? – fledgling

+0

你可能想要寻找你的字符串之间的编辑距离 – njzk2

+0

http://stackoverflow.com/questions/24572299/using-python-efficiently-to-calculate-hamming-distances? –

回答

1

要回答你的标题提出的问题,就可以得到匹配的字符数的计数在两个字符串:

In [1]: s1 = 'Can We Live (feat. Cece Rogers) [Joke Instrumental Mix]' 
In [2]: s2 = 'Can We Live (feat. Cece Rogers) Joke Instrumental Mix' 

In [3]: if len(s1) > len(s2):  # swap strings so that s1 is shortest 
    .....:  s1, s2 = s2, s1 
    .....:  

In [4]: sum(c1==s2[i] for i, c1 in enumerate(s1)) 
Out[4]: 32 

但是这未必是相似的您的目的足够好的措施。如果是这种情况,请查看Levenshtein distance及其在distance module中的实施。

编辑:@Veedrac是完全正确的:无交换的更简单,一个行的解决方案是:

sum(c1 == c2 for c1, c2 in zip(s1, s2)) 

zip忽略较长序列资料)。

+0

或者只是'sum(c1 == c2 for c1,c2 in zip(s1,s2))''没有交换的东西。哎呀,甚至只是用'来自operator import eq'的sum(map(eq,s1,s2))''。 – Veedrac