2012-04-05 112 views
5

在这个程序中,我试图使我有一个表达式(例如“I = 23mm”或“H = 4V”),我试图提取23或4),以便我可以把它变成一个整数。从一个单词字符串中提取一个数字

我依然会碰到的问题是,由于表达我试图把号码的开出的是1个字,我不能使用分裂()或任何东西。

一个例子,我看到,但难道不工作是 -

I="I=2.7A" 
[int(s) for s in I.split() if s.isdigit()] 

这难道不工作,因为它只需将数字是由空格分隔。如果int078vert这个词中有一个数字,它就不会提取它。另外,我的地址没有空格来分隔。

我想一个是这个样子,

re.findall("\d+.\d+", "Amps= 1.4 I") 

但它没有工作,要么,因为正在传递的数量并不总是2位。它可能是5或类似13.6的东西。

什么代码,我需要写那么,如果我传递一个字符串,如

I="I=2.4A" 

I="A=3V" 

所以,我只能提取数出这个字符串? (并对其进行操作)?没有可以划定的空格或其他常量字符。

+0

它看起来像你试图解决这个整数和十进制数。每个字符串总是只有一个数字吗? – yoozer8 2012-04-05 23:16:11

+0

是的。每个字符串将始终有1个数字,但可能有多个小数点来表示该数字。 – Kyle 2012-04-06 02:10:54

回答

11
>>> import re 
>>> I = "I=2.7A" 
>>> s = re.search(r"\d+(\.\d+)?", I) 
>>> s.group(0) 
'2.7' 
>>> I = "A=3V" 
>>> s = re.search(r"\d+(\.\d+)?", I) 
>>> s.group(0) 
'3' 
>>> I = "I=2.723A" 
>>> s = re.search(r"\d+(\.\d+)?", I) 
>>> s.group(0) 
'2.723' 
+0

非常感谢。工作得很好。 – Kyle 2012-04-06 02:10:00

3

RE可能是这个不错,但作为一个RE的答案已经发布,我要你的非正则表达式的例子,并修改它:


One example I saw but wouldnt work was - 

I="I=2.7A" 
[int(s) for s in I.split() if s.isdigit()] 

好事是split()可以接受参数。试试这个:

extracted = float("".join(i for i in I.split("=")[1] if i.isdigit() or i == ".")) 

顺便说一句,这里就是你提供的RE的细分:

"\d+.\d+" 
\d+ #match one or more decimal digits 
. #match any character -- a lone period is just a wildcard 
\d+ #match one or more decimal digits again 

一个办法(正确地)做这将是:

"\d+\.?\d*" 
\d+ #match one or more decimal digits 
\.? #match 0 or 1 periods (notice how I escaped the period) 
\d* #match 0 or more decimal digits 
+0

将拆分的解决方案是很整齐:d。 +1 – 2012-04-06 01:08:33

+0

欣赏不同的方法。 +1 – Kyle 2012-04-06 02:09:23

相关问题