-2

I have two strings 'I go to school and play badminton in the evening' and 'I go to e2 and r2 in the evening'. How to find e2 = 'school' and r2 = 'play badminton'. I tried using for loops but looking for a more elegant way to do it.

Curious
  • 43
  • 9

3 Answers3

2
a = set('I go to school and play badminton in the evening'.split(' '))
b = set('I go to and in the evening'.split(' '))

print(a - b)
>>> {'badminton', 'school', 'play'}

edit for your edit:

If you would also like to name them directly from the parsing, you would need to tweak the input a bit and probably also use: Does Python have an ordered set?

Or Y
  • 2,088
  • 3
  • 16
0
a = "I go to school and play badminton in the evening"
b = "I go to and in the evening" 
a_set = set(a.split())
b_set = set(b.split())
print(a_set.difference(b_set))
# {'badminton', 'school', 'play'}
gnahum
  • 426
  • 1
  • 5
  • 13
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Aug 10 '20 at 06:22
0

Given that pattern may change every time along with the string it turns out to be a string compare problem. Quite elegant solution may be provided with use of difflib.

str1 = "I go to e2 and r2 in the evening"
str2 = "I go to school and play badminton in the evening"

from difflib import SequenceMatcher
s = SequenceMatcher(None, str1, str2)
diff = [(str1[opcode[1]:opcode[2]], str2[opcode[3]:opcode[4]])
        for opcode in s.get_opcodes() if opcode[0] == 'replace']
print(diff)
# [('e2', 'school'), ('r2', 'play badminton')]

Previous solution:
I think most apropriate and flexible in this case would be using regex search.

import re
pattern = "I go to (.*) and (.*) in the evening"
string = "I go to school and play badminton in the evening"
m = re.match(pattern, string)
e2 = m.groups()[0]
r2 = m.groups()[1]
result = e2 == 'school' and r2 == 'play badminton'
print(result)
apawelek
  • 131
  • 1
  • 7
  • The pattern may change everytime along with the string. – Curious Aug 09 '20 at 16:27
  • I answered your question. It's not specified in your question how pattern may change. Please clarify it or provide example. – apawelek Aug 09 '20 at 16:37
  • I think I understand what you mean now. Phrases like 'e2' or 'r2' or other apper explicitly in a text in various places - right? – apawelek Aug 09 '20 at 19:56