Python: 使用正则表达式过滤自学习程序

我正在制作一个具备小型自学习功能的程序,现在我想从输出中获取“信息”,例如:

>>>#ff0000 is the hexcode for the color red

我想使用正则表达式来过滤用户填写的句子is the hexcode for the color,并提取颜色名称和十六进制代码。我在下面提供了一个小代码示例,展示我想实现的效果:

#main.pystrInput = raw_input("Please give a fact:")if "{0} is the hexcode for the color {1}" in strInput:    #  {0} 是颜色的名称    #  {1} 是颜色的十六进制代码    print "You give me an color"if "{0} is an vehicle" in strInput:    #  {0} 是一种交通工具    print "You give me an vehicle"

使用正则表达式是否可以实现这一点?使用正则表达式的最佳方法是什么?


回答:

您可以在标准库文档中阅读关于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

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注