[英]How can I count character matches in a string in 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
已阅读以下内容: perl中字符串之间的字符匹配计数
想用Python来做。
要回答标题中的问题,您可以使用以下两个方法获得两个字符串中匹配字符数的计数:
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
模块中的实现。
编辑:@Veedrac是完全正确的:一个没有交换的更简单的单行解决方案是:
sum(c1 == c2 for c1, c2 in zip(s1, s2))
( zip
忽略较长序列中的项目)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.