检查python中两个字符串之间的交集

问题描述 投票:2回答:3

我正在尝试使用Python检查两个字符串之间的交集。我定义了这个函数:

def check(s1,s2):
    word_array = set.intersection(set(s1.split(" ")), set(s2.split(" ")))
    n_of_words = len(word_array)
    return n_of_words

它适用于一些示例字符串,但在这种特定情况下:

d_word = "BANGKOKThailand"
nlp_word = "Despite Concerns BANGKOK"

print(check(d_word,nlp_word))

我得到了0.我错过了什么?

python arrays string string-comparison set-intersection
3个回答
0
投票

设置一个包含单个字符串,设置两个3个字符串,字符串"BANGKOKThailand"不等于字符串"BANGKOK"


0
投票

我可以看到两个可能是错误:

n_of_words = len(array)

应该

n_of_words = len(word_array)

d_word = "BANGKOKThailand"

错过了中间的空间

"BANGKOK Thailand"

修复这两个更改给了我1的结果。


0
投票

无论这个部分在哪里,我都在寻找2个弦的最大共同部分。

def get_intersection(s1, s2): 
    res = ''
    l_s1 = len(s1)
    for i in range(l_s1):
        for j in range(i + 1, l_s1):
            t = s1[i:j]
            if t in s2 and len(t) > len(res):
                res = t
    return res
#get_intersection(s1, s2)

也适用于此示例:

>>> s1 = "BANGKOKThailand"
>>> s2 = "Despite Concerns BANGKOK"
>>> get_intersection('aa' + s1 + 'bb', 'cc' + s2 + 'dd')
'BANGKOK'
© www.soinside.com 2019 - 2024. All rights reserved.