Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

Find intersection of words in two strings in python

I have two strings containing words: 'dan esh gah' and 'da nesh gah'

I need the intersection words, which is 'gah' in this case.

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.

question from:https://stackoverflow.com/questions/65888303/find-intersection-of-words-in-two-strings-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do the intersection using & on set() 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 using str.split(). set() will convert the list to set object, on which you can find intersection between two sets using &.

If you prefer functional style, you can use set().intersection() to get the same result:

>>> set(s1.split()).intersection(s2.split())
set(['gah'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...