我必须管理我对语音助手说的所有可能的家庭自动化命令,例如:
使用单个正则表达式,我必须能够细分每种命令:
使用my previous question中的正则表达式修改后的用途,我得到:
>>> print(re.search(r'(accendi.+)(spegni.+)(imposta.+)', "accendi la luce in corridoio, spegni la luce in camera e imposta 20 in salotto").groups())
('accendi la luce in corridoio, ', 'spegni la luce in camera e ', 'imposta 20 in salotto')
可以,但是不适用于其他命令:
>>> print(re.search(r'(accendi.+)(spegni.+)(imposta.+)', "accendi la luce in camera e cameretta, spegni la luce in corridoio").groups())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
>>> print(re.search(r'(accendi.+)(spegni.+)(imposta.+)', "accendi la luce in salotto").groups())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
答案 0 :(得分:0)
尝试此正则表达式。它不需要所有三个定界符都存在,但是,如果确实存在,则将正确拆分命令:
(accendi(?:(?!spegni).)+)(spegni(?:(?!imposta).)+)?(imposta.+)?
(accendi #start first group, match accendi
(?: #start non-capturing group
(?! #start negative lookahead
spegni #ensure the next characters aren't spegni
) #end negative lookahead
. #match any character
)+ #end non-capturing group, repeat 1 or more times
) #end first capture group
(spegni #start second group, match spegni
(?: #start non-capturing group
(?! #start negative lookahead
imposta #ensure the next characters aren't imposta
) #end negative lookahead
. #match any character
)+ #end non-capturing group, repeat 1 or more times
)? #end second capture group, make it optional
(imposta #start third capture group, match imposta
.+ #match anything 1 or more times
)? #end third capture group, make optional