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
)
)
下面是一种使用regexp的方法:
或者另一种更简单的方法是使用如下regexp:
(我在写了前一篇文章之后就想到了这篇文章:-p)
上一个regexp的完整解释:
对于提取数值,可以使用re
相关问题 更多 >
编程相关推荐