1

我需要将源字符串转换为目标字符串,并表达与对源字符串的操作 (D,A,TYPE) 即(删除、添加、PREFIX\SUFFIX)相同的操作,这将在应用这些操作时将其转换为目标字符串源字符串的后缀,或源字符串的前缀

例如:

activities->activity
(ies,y,suffix)

center->centre
(er,re,suffix)

solutions->solution
(s,None,suffix)

solution ->solutions
(None,s,suffix)

could->would
(c,w,prefix)

以下代码确实获得了后缀,但也获得了所有其他匹配项,但我只需要后缀,除此之外它不会按照我的要求输出正确的格式。

from difflib import SequenceMatcher
a = "ACTIVITY"
b = "ACTIVITIES"


s = SequenceMatcher(None, a, b)
for tag, i1, i2, j1, j2 in s.get_opcodes():
   print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
          (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))

此外,如果没有足够的后缀/前缀匹配,我也不需要输出任何更正,例如:字符串足够,超出不应该产生匹配,这可能来自:

difflib.SequenceMatcher(None,'especially','particularly').ratio()
4

2 回答 2

2

这不需要 difflib,因为它可以通过查找公共前缀或后缀并将其从字符串中删除来完成。考虑:

>>> from os.path import commonprefix
>>> c = commonprefix(['activities', 'activity'])
>>> c
'activit'
>>> [v[len(c):] for v in ['activities', 'activity']]
['ies', 'y']

由于我没有commonsuffix函数,我只是简单地反转字符串,然后应用commonprefix函数:

>>> c = commonprefix(['could'[::-1], 'would'[::-1]])
>>> c
'dluo'
>>> [v[len(c):][::-1] for v in ['could'[::-1], 'would'[::-1]]]
['c', 'w']

将其组合成一个函数:

from os.path import commonprefix

def suffix_prefix(a, b):

   pre = commonprefix([a, b])
   suf = commonprefix([a[::-1], b[::-1]])
   if len(pre) > len(suf):
       return tuple(v[len(pre):] for v in (a, b)) + ('suffix',)
   else:
       return tuple(v[len(suf):][::-1] for v in (a[::-1], b[::-1])) + ('prefix',)

print suffix_prefix('activities', 'activity')
print suffix_prefix('could', 'would')
print suffix_prefix('solutions', 'solution')

印刷:

('ies', 'y', 'suffix')
('c', 'w', 'prefix')
('s', '', 'suffix')

我将把字符串格式留给你。

于 2015-09-06T15:55:34.873 回答
1

我想你可能有点过于复杂了。在 python 中找到两个字符串的共享后缀相当容易,而无需使用difflib. 有关示例,请参阅此 stackexchange 问题。特别是,这在os模块中实现为os.path.commonprefix. 使用它,我们可以找到共享前缀的两个字符串的后缀差异或共享后缀的两个字符串中的前缀差异(第二种方法只是通过反转字符串并使用第一种方法)。

这是一个示例(当然可以整理一下):

import os

def find_change(string_1, string_2):
    shared_prefix = os.path.commonprefix([string_1, string_2])

    if len(shared_prefix) > 0:
        return "{}->{}\n({},{},{})".format(string_1, string_2, string_1[len(shared_prefix):],string_2[len(shared_prefix):], "SUFFIX")

    string_1_reversed = string_1[::-1]
    string_2_reversed = string_2[::-1]

    shared_suffix_reversed = shared_prefix = os.path.commonprefix([string_1_reversed, string_2_reversed])

    if len(shared_suffix_reversed) > 0:
        shared_suffix = shared_suffix_reversed[::-1]
        return "{}->{}\n({},{},{})".format(string_1, string_2, string_1[:-len(shared_suffix)], string_2[:-len(shared_suffix)], "PREFIX")

    return None 

print(find_change("could", "would"))
print(find_change("hello", "helmet"))
于 2015-09-06T15:03:37.330 回答