Find the contact and non-contact part of two lines

I have two examples of a pair of strings

YHFLSPYVY      # answer
   LSPYVYSPR   # prediction
+++******ooo


  YHFLSPYVS    # answer
VEYHFLSPY      # prediction
oo*******++

As stated above, I would like to find the overlapping region ( *) and the disjoint region in the answer ( +) and the prediction ( o).

How can I do this in Python?

I'm stuck with this

import re
# This is of example 1
ans = "YHFLSPYVY"
pred= "LSPYVYSPR"
matches = re.finditer(r'(?=(%s))' % re.escape(pred), ans)
print [m.start(1) for m in matches]
#[]

The answer I hope to get, for example, is 1:

plus_len = 3
star_len = 6
ooo_len = 3
+4
source share
2 answers

Easy with difflib.SequenceMatcher.find_longest_match:

from difflib import SequenceMatcher

def f(answer, prediction):
    sm = SequenceMatcher(a=answer, b=prediction)
    match = sm.find_longest_match(0, len(answer), 0, len(prediction))
    star_len = match.size
    return (len(answer) - star_len, star_len, len(prediction) - star_len)

The function returns a 3-tuple of integers (plus_len, star_len, ooo_len):

f('YHFLSPYVY', 'LSPYVYSPR') -> (3, 6, 3)
f('YHFLSPYVS', 'VEYHFLSPY') -> (2, 7, 2)
+3
source

You can use difflib:

import difflib

ans = "YHFLSPYVY"
pred = "LSPYVYSPR"

def get_overlap(s1, s2):
     s = difflib.SequenceMatcher(None, s1, s2)
     pos_a, pos_b, size = s.find_longest_match(0, len(s1), 0, len(s2))
     return s1[pos_a:pos_a+size]

overlap = get_overlap(ans, pred)
plus = ans.replace(get_overlap(ans, pred), "")
oo = pred.replace(get_overlap(ans, pred), "")

print len(overlap)
print len(plus)
print len(oo)
+1
source

Source: https://habr.com/ru/post/1649281/


All Articles