如何在两个字符串中找到匹配的单词



我有两个类似的字符串

My name is BogdanBogdan and I am from Russia

我需要从这个字符串中获取单词Bogdan。我总是知道第一句话的结尾是什么。

我怎么能找到这种重叠。

我的解决方案返回类似的字符

res = list(set('My name is Bogdan').intersection(set('Bogdan and i am from Russia')))
print(res)

返回

['i', 'n', 'g', 'm', ' ', 's', 'B', 'a', 'd', 'o']

首先最大限度地重叠两个字符串,然后通过减少重叠进行迭代:

def find_overlap(s1, s2):
for i in range(len(s1)):
test1, test2 = s1[i:], s2[:len(s1) - i]
if test1 == test2:
return test1
s1, s2 = "My name is Bogdan", "Bogdan and I am from Russia"
find_overlap(s1, s2)
# 'Bogdan'
s1, s2 = "mynameisbogdan", "bogdanand"
find_overlap(s1, s2)
# 'bogdan'

正如您所看到的,如果两个字符串不包含空格,这也适用。

它有O(n(运行时,但如果您首先确定两个字符串中的哪一个更短,则可以减少为O(min(n,m((。

如果你希望找到的字符串比两个字符串中最短的字符串短得多,你可以将其设为偶数O(k(,其中k是要找到的字符串的长度,从最小重叠开始:

def find_overlap(s1, s2):
for i in range(1, len(s1) + 1):
if i == len(s2):
return None
test1, test2 = s1[-i:], s2[:i]
if test1 == test2:
return test1

可以使用集合交集

l1="My name is Bogdan"
l2="Bogdan and I am from Russia"
print(set(l1.split())&set(l2.split())) # set('Bogdan')

列表理解

l1="My name is Bogdan"
l2="Bogdan and I am from Russia"
[i for i in l1.split() if i in l2.split()] ['Bogdan']

其他选项,带有for循环:

def shared_words(s1, s2):
res = []
l_s1, l_s2 = set(s1.split()), set(s2.split())
for ss1 in l_s1:
if ss1 in l_s2: res.append(ss1)
return res

应用于字符串:

s1 = "My name is Bogdan"
s2 = "Bogdan and I am from Russia"
print(shared_words(s1, s2)) #=> ['Bogdan']

或者,使用正则表达式只拆分单词:

import re
def shared_words(s1, s2):
res = []
l_s1, l_s2 = set(re.findall(r'w+',s1)), set(re.findall(r'w+',s2))
for ss1 in l_s1:
if ss1 in l_s2: res.append(ss1)
return res

获取:

s1 = "My name is Bogdan, I am here"
s2 = "Bogdan and I am from Russia."
print(shared_words(s1, s2)) #=> ['Bogdan', 'I', 'am']

相关内容

  • 没有找到相关文章

最新更新