2012-04-05 160 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

相關問題