A regular expression search is one way of quickly doing what you want, with a pattern made from the different device names.
import re
def find_with_regex(command, pattern):
return list(set(re.findall(pattern, command, re.IGNORECASE)))
I would also suggest building the reversed dictionary of device: name
shape, maybe it would help quickly finding the code name of a given device.
devices = [{'name': 'fan light'}, {'name': 'fan'}]
# build a quick-reference dict with device>name structure
transformed = {dev: name for x in devices for name, dev in x.items()}
# should also help weeding out duplicated devices
# as it would raise an error as soon as it fids one
# print(transformed)
# {'fan light': 'name', 'fan': 'name'}
Special thanks to buddemat for pointing out that device names to be in a particular order for this solution to work, fixed it with reversed(sorted(...
on the pattern making line from the next code block.
Testing the function
test_cases = [
'Turn on fan light',
'Turn on fan light and fan',
'Turn on fan and fan light',
'Turn on fan and fan',
]
pattern = '|'.join(reversed(sorted(transformed)))
for command in test_cases:
matches = find_with_regex(command, pattern)
print(matches)
Output
['fan light']
['fan', 'fan light']
['fan', 'fan light']
['fan']
CLICK HERE to find out more related problems solutions.