[英]Find intersection of words in two strings in python
I have two strings containing words: 'dan esh gah'
and 'da nesh gah'
我有两个包含单词的字符串:
'dan esh gah'
和'da nesh gah'
I need the intersection words, which is 'gah'
in this case.我需要交叉词,在这种情况下是
'gah'
。
I used this code我用了这段代码
vocab=['dan esh gah']
gold=['da nesh gah']
s1 = ''.join(vocab)
s2=''.join(gold)
a=[]
track=[]
for k in range(len(s1)+1):
if k!=0:
for ka in range(0,len(s1)+1,k):
if s1[ka:ka+k] in s2:
track.append((len(s1[ka:ka+k])+1,s1[ka:ka+k]))
intersect=max(track)[1]
print(intersect)
but the answer is wrong:但答案是错误的:
sh ga
Please help me to solve this problem.请帮我解决这个问题。
You can do the intersection using &
onset()
object:您可以使用
&
onset()
object 进行交集:
>>> s1='da nesh gah'
>>> s2='dan esh gah'
>>> set(s1.split()) & set(s2.split())
set(['gah'])
Here, I am firstly converting the string to list of words usingstr.split()
.在这里,我首先使用
str.split()
将字符串转换为单词列表。 set()
will convert the list to set object , on which you can find intersection between two sets using &
. set()
将列表转换为设置 object ,您可以在其上使用&
找到两个集合之间的交集。
If you prefer functional style, you can use set().intersection()
to get the same result:如果您更喜欢函数式风格,可以使用
set().intersection()
来获得相同的结果:
>>> set(s1.split()).intersection(s2.split())
set(['gah'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.