【问题标题】:Calculate word overlap from two words in two directions in python在python中计算两个方向上两个单词的单词重叠
【发布时间】:2017-05-05 15:18:06
【问题描述】:

所以我有两个词。我想编写一个函数来找到从每个单词到另一个单词的最大重叠。示例:

words = ['AAB', 'BAA']
find_overlap('AAB', 'BAA')

应该输出 B 和大小 1,并且:

find_overlap('BAA', 'AAB')

应该输出 AA 和 size 2。有什么建议吗?

编辑:所以我尝试了 python 中的 difflib.SequenceMatcher,但我不明白输出。

s1 = "AAB"
s2 = "BAA"
s = difflib.SequenceMatcher(None, s1, s2)
pos_a, pos_b, size = s.find_longest_match(0, len(s1), 0, len(s2)) 
print(pos_a, pos_b, size)

【问题讨论】:

  • 先检查最大可能的重叠,然后迭代到越来越小的重叠。
  • @Moberg 这表明要检查 War and PeaceCrime and Punishment 的完整文本的最大重叠,我们将首先检查对于几十万个字符的重叠,然后向下工作。听起来效率不是很高。重叠的长度可能为 0。
  • @JohnColeman 不,效率不高。虽然这意味着在 WaP 中找到第一个出现的 CapP 的第一个字母并按照自己的方式进行操作。当然,一旦它们不匹配,就会跳到下一个出现。还有哪些其他方法? :)
  • 请检查编辑。
  • 尽管difflib 看起来应该是相关的,但我不确定它是否真的相关。 find_longest_match 似乎没有帮助,除非最长的匹配恰好出现在一个字符串的末尾并同时出现在另一个字符串的开头。

标签: python


【解决方案1】:

对于较短的字符串,简单的方法可能就足够了。比如@Moberg的想法可以这样实现

def largest_overlap(s1,s2):
    n = min(len(s1),len(s2))
    for i in range(n,0,-1):
        if s2.startswith(s1[-i:]):
            return s1[-i:]
    return ''

一些测试用例:

print("BAA, AAB =>", largest_overlap("BAA", "AAB"))
print("AAB, BAA =>", largest_overlap("AAB", "BAA"))
print("AAA, BB =>", largest_overlap("AAA", "BB"))
print("AA, AABB =>", largest_overlap("AA", "AABB"))
print("hello world, world peace =>", largest_overlap("hello world", "world peace"))

输出:

BAA, AAB => AA
AAB, BAA => B
AAA, BB => 
AA, AABB => AA
hello world, world peace => world

对于更长的字符串,您可能需要更复杂的算法,类似于this

【讨论】:

  • 谢谢。如何修改它以输出不重叠的整个单词,例如 BAA, AAB => AA ,我也想要 BAAB。
  • @LoraSinha 如果s 是返回的重叠,那么s1 + s2[len(s):] 是连接的两个单词,重叠只出现一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 2012-01-06
相关资源
最近更新 更多