2017-12-27 1518 views
-3

我是新來的正則表達式獲取貨幣數字,我試圖用re.findall提取貨幣般的數字(整數或1漂浮或2DP)從形式的字符串:Python的正則表達式:從一個字符串

'1000 - 2000' , '1000 -', '1000.4' 

我一直在努力尋找一個正則表達式模式,讓我從字符串的所有數字提取到一個單獨的列表,並希望在這個問題上的任何幫助。

例如,

import re 

pattern = '^\d*[.,]?\d*$' 
temp = ['1000.5 - 2000.55'] 
strings = re.findall('^\d*[.,]?\d*$', temp[0]) 

輸出我得到的是一個空列表,[]

我想獲得

strings = ['1000.5','2000.55'] 

,然後想將它們轉換爲浮動與

nums = [float(i) for i in strings] 
+2

你能提供樣品的輸入和預期的輸出?您的問題將被視爲*太寬泛*否則。 – ctwheels

+0

你是否也想用1個小數點的浮點數? – Marathon55

+0

此外,當你說'與2dp'你的意思是,如果你有一些像'1.123'你想獲得'1.12'或要忽略它完全這樣你沒有它的輸出顯示?此外,如果有'1.126',假設你要切斷這樣,你得到'1.12'最後一個數字:你想'1.12'或'1.13'的舍入值? – ctwheels

回答

0
import re 

temp = ['1000.5 - 2000.55'] 
strings = re.findall('\d+(?:[.,]\d*)?', temp[0]) 
nums = [float(i) for i in strings] 
print(nums) # [1000.5, 2000.55] 

demo

0

你可以用[0-9.]+

import re 
pattern=r'[0-9.]+' 
temp = ['1000.5 - 2000.55'] 
for i in temp: 
    print(list(map(lambda x:float(x),re.findall(pattern,i)))) 

輸出:

[1000.5, 2000.55] 

你也可以做一個行:

print([list(map(lambda x:float(x),re.findall(pattern,i))) for i in temp][0]) 

輸出:

[1000.5, 2000.55] 
0

你可以試試這個:

import re 
temp = ['1000.5 - 2000.55'] 
final_data = map(float, re.findall('\d+\.\d+|\d+', temp[0])) 

輸出:

[1000.5, 2000.55]