将更改的字符位置映射回python中的原始字符串

时间:2018-08-22 13:06:16

标签: python string sequence matcher difflib

输入字符串1:11245--2

输入字符串2:11245--4

修改后的IP字符串1(去除特殊字符):112452

修改后的IP String2(删除特殊字符):112454

在(修改的IP字符串1,修改的IP字符串2)上应用了diff lib序列匹配器

使用Sequence Matcher get_opcodes()方法,我可以使用操作码作为“替换”来获取更改的字符(即5)的位置。

现在,如何将已更改字符的位置映射回原始输入字符串(即7)?

代码示例:

from difflib import SequenceMatcher

input_string1 = "11245--2"

input_string2 = "11245--4"

modified_string1 = "112452"

modified_string2 = "112454"

sm = SequenceMatcher(None,modified_string1,modified_string2)

for opcode in sm.get_opcodes():
    if(opcode[0] == "replace"):
        print("change_char_in_s1:{} {}".format(opcode[1],opcode[2]))
        print("change_char_in_s2:{} {}".format(opcode[3],opcode[4]))

我使用序列匹配器是因为我需要在应用程序中匹配多少字符串的分数。

0 个答案:

没有答案