Как мне сопоставить ключевое слово в строке и, если он найден, искать варианты, связанные с ключевым словом?
Это ключевые слова и опции, которые мне нужно найти:
Standard
Snow <start date> <end date> Example: <24/12/2010> <9/1/2011>
Rain <all day> or <start time> <end time> Example: <8:30> <10:45> or <10:30> <13:00>
Wind <all day> or <start time> <end time> Example: <8:30> <10:45> or <10:30> <13:00>
Вот фрагмент кода, с которым я экспериментировал:
# This is the string that should match one of those shown above.
# Btw the string is the result of user input from a different process.
mystring = 'Rain <8:30> <10:45>'
# Validate string
if mystring == '':
print 'Error: Missing information'
sys.exit(1)
# Look for keywords in mystring
Regex = re.compile(r'''
^(\w+)
\D+
(\d)
\D+
(\d{2})
''', re.VERBOSE)
match = Regex.search(mystring)
# print matching information for debugging
print 'match: ' + str(match)
print 'all groups: ' + match.group(0)
print 'group 1: ' + match.group(1)
print 'group 2: ' + match.group(2)
print 'group 3: ' + match.group(3)
# if match.group(1) equates to one of the keywords
# (e.g. Standard, Snow, Rain or Wind)
# check that the necessary options are in mystring
if match.group(1) == 'Standard':
print 'Found Standard'
# execute external script
elif match.group(1) == 'Snow':
print 'Found Snow'
# check for options (e.g. <start date> <end date>
# if options are missing or wrong sys.exit(1)
# if options are correct execute external script
elif match.group(1) == 'Rain':
print 'Found Rain'
# check for options (e.g. <all day> or <start time> <end time>
# if options are missing or wrong sys.exit(1)
# if options are correct execute external script
elif match.group(1) == 'Wind':
print 'Found Wind'
# check for options (e.g. <all day> or <start time> <end time>
# if options are missing or wrong sys.exit(1)
# if options are correct execute external script
Я знаю, что мое регулярное выражение в приведенном выше коде не работает должным образом.Это мой первый правильный скрипт на python, и я не уверен, какие методы я должен использовать для выполнения своей задачи.
Спасибо.