从Python中提取数字数据

2024-06-25 22:50:10 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有几行字:

1,000 barrels
5 Megawatts hours (MWh)
80 Megawatt hours (MWh) (5 MW per peak hour).

捕获数字元素(即第一个实例)和第一个括号(如果存在)的最佳方法是什么。你知道吗

我目前的方法是对每个' '. and str.isalpha使用拆分字符串来查找非alpha元素。但是,不知道如何获得论文的第一个条目。你知道吗


Tags: 实例方法元素数字括号mwbarrelsper
2条回答

下面是一种使用regexp的方法:

import re

text = """1,000 barrels
5 Megawatts hours (MWh)
80 Megawatt hours (MWh) (...)"""

r_unit = re.compile("\((\w+)\)")
r_value = re.compile("([\d,]+)")

for line in text.splitlines():
    unit = r_unit.search(line)
    if unit:
        unit = unit.groups()[0]
    else:
        unit = ""
    value = r_value.search(line)
    if value:
        value = value.groups()[0]
    else:
        value = ""
    print value, unit

或者另一种更简单的方法是使用如下regexp:

r = re.compile("(([\d,]+).*\(?(\w+)?\)?)")
for line, value, unit in r.findall(text):
    print value, unit

(我在写了前一篇文章之后就想到了这篇文章:-p)

上一个regexp的完整解释:

(      <- LINE GROUP
 (     <- VALUE GROUP
  [    <- character grouping (i.e. read char is one of the following characters)
   \d  <- any digit
   ,   <- a comma
  ]
  +    <- one or more of the previous expression
 )
 .     <- any character
 *     <- zero or more of the previous expression
 \(    <- a real parenthesis
 ?     <- zero or one of the previous expression
 (     <- UNIT GROUP
  [
   \w  <- any alphabetic/in-word character
   +   <- one or more of the previous expression
  ]
 )
 ?     <- zero or one of the previous expression
 \)    <- a real ending parenthesis
 ?     <- zero or one of the previous expression
 )
)

对于提取数值,可以使用re

import re
value = """1,000 barrels
           5 Megawatts hours (MWh)
           80 Megawatt hours (MWh) (5 MW per peak hour)"""
re.findall("[0-9]+,?[0-9]*", value)

相关问题 更多 >