我有一个Python字符串,其中包含我想要使用正则表达式提取的信息。
示例:
"The weather is 75 degrees with a humidity of 13%"
我想拉出“75”和“13”。以下是我迄今为止在Python中尝试过的内容。
import re
str = "The weather is 75 degrees with a humidity of 13%"
m = re.search("The weather is \d+ degrees with a humidity of \d+%", str)
matched = m.group()
然而,这显然匹配整个字符串而不仅仅是我想要的部分。如何提取我想要的数字?我已经研究了反向引用,但它似乎只适用于正则表达式模式本身。
答案 0 :(得分:2)
m = re.search("The weather is (\d+) degrees with a humidity of (\d+)%", str)
matched = m.groups()
你需要在括号中包装你想要的东西......
>>> s1 = "The weather is 75 degrees with a humidity of 13%"
>>> m = re.search("The weather is (\d+) degrees with a humidity of (\d+)%", s1)
>>> m.groups()
('75', '13')
或只是使用findall
来获取任何字符串中的数字
>>> re.findall("\d+",s1)
['75', '13']
答案 1 :(得分:2)
也许您想使用命名组?
>>> m = re.search("The weather is (?P<temp>\d+) degrees with a humidity of (?P<humidity>\d+)%", s1)
>>> m.group('temp')
'75'
>>> m.group('humidity')
'13'
答案 2 :(得分:0)
如果要从文本中提取类型化数据,例如数字,parse
是一个非常有用的库。在许多方面,它与字符串格式相反。它需要一种模式,并会进行类型转换。
最简单的是,它可以避免担心正则表达式组等等。
>>> s = "The weather is 75 degrees with a humidity of 13%"
>>> parse("The weather is {} degrees with a humidity of {}%", s)
<Result ('75', '13') {}>
Result
对象很容易使用:
>>> r = _
>>> r[0]
'75'
我们可以通过指定字段名称和/或类型转换来做得更好。以下是将结果整数整理所需的全部内容:
>>> parse("The weather is {:d} degrees with a humidity of {:d}%", s)
<Result (75, 13) {}>
如果我们想使用非索引键,则添加字段名称:
>>> parse("The weather is {temp:d} degrees with a humidity of {humidity:d}%", s)
<Result () {'temp': 75, 'humidity': 13}>
>>> r = _
>>> r['temp']
75