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。
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。
要回答你的標題提出的問題,就可以得到匹配的字符數的計數在兩個字符串:
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
忽略較長序列資料)。
或者只是'sum(c1 == c2 for c1,c2 in zip(s1,s2))''沒有交換的東西。哎呀,甚至只是用'來自operator import eq'的sum(map(eq,s1,s2))''。 – Veedrac
你到目前爲止試過的東西? – fledgling
你可能想要尋找你的字符串之間的編輯距離 – njzk2
http://stackoverflow.com/questions/24572299/using-python-efficiently-to-calculate-hamming-distances? –