Python:用于自学习程序的正则表达式过滤
我正在制作一个程序,它有一个小的自我学习方式,但现在我想从输出中获得“信息”,如:Python:用于自学习程序的正则表达式过滤,python,regex,pattern-matching,artificial-intelligence,Python,Regex,Pattern Matching,Artificial Intelligence,我正在制作一个程序,它有一个小的自我学习方式,但现在我想从输出中获得“信息”,如: >>>#ff0000 is the hexcode for the color red 我想用正则表达式过滤用户填写的这句话是颜色的十六进制代码,并且我检索颜色的名称和十六进制代码。我在下面写了一个小代码,说明我希望如何工作: #main.py strInput = raw_input("Please give a fact:") if "{0} is the hexcode for th
>>>#ff0000 is the hexcode for the color red
我想用正则表达式
过滤用户填写的这句话是颜色的十六进制代码
,并且我检索颜色的名称和十六进制代码。我在下面写了一个小代码,说明我希望如何工作:
#main.py
strInput = raw_input("Please give a fact:")
if "{0} is the hexcode for the color {1}" in strInput:
# {0} is the name of the color
# {1} is the hexcode of the color
print "You give me an color"
if "{0} is an vehicle" in strInput:
# {0} is an vehicle
print "You give me an vehicle"
使用regular expressions
是否可以实现这一点,使用regular expressions
的最佳方法是什么?您可以在标准库文档中阅读。这里,我使用命名组将匹配的值存储到一个字典结构中,其中包含一个您选择的键
>>> import re
>>> s = '#ff0000 is the hexcode for the color red'
>>> m = re.match(r'(?P<hexcode>.+) is the hexcode for the color (?P<color>.+)', s)
>>> m.groupdict()
{'color': 'red', 'hexcode': '#ff0000'}
>>重新导入
>>>s=“#ff0000是红色的十六进制代码”
>>>m=re.match(r’(?P++)是颜色(?P++)的十六进制代码,s)
>>>m.groupdict()
{'color':'red','hexcode':'#ff0000'}
请注意,如果使用正则表达式没有匹配项,则此处的m
对象将是None