Python: 自学程序的正则表达式过滤
Python: Reggular Expressions filtering for Self Learning program
我正在制作一个具有自学小方法的程序,但现在我想从输出中获得 "information",例如:
>>>#ff0000 is the hexcode for the color red
我想用 reggular expressions
过滤用户填写了这句话 is the hexcode for the color
,并且我检索了颜色的名称和十六进制代码。我在我想要的工作方式下面放了一小段代码:
#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"
reggular expressions
是否可行,reggular expressions
的最佳方法是什么?
您可以在标准库文档中阅读有关 regular expressions in Python 的内容。在这里,我使用命名组将匹配值存储到具有您选择的键的字典结构中。
>>> 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'}
请注意,如果使用正则表达式没有匹配项,则此处的 m
对象将为 None
。
我正在制作一个具有自学小方法的程序,但现在我想从输出中获得 "information",例如:
>>>#ff0000 is the hexcode for the color red
我想用 reggular expressions
过滤用户填写了这句话 is the hexcode for the color
,并且我检索了颜色的名称和十六进制代码。我在我想要的工作方式下面放了一小段代码:
#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"
reggular expressions
是否可行,reggular expressions
的最佳方法是什么?
您可以在标准库文档中阅读有关 regular expressions in Python 的内容。在这里,我使用命名组将匹配值存储到具有您选择的键的字典结构中。
>>> 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'}
请注意,如果使用正则表达式没有匹配项,则此处的 m
对象将为 None
。