Python正则表达式提取浮点值
我的数据中有带浮点数的字符串,比如Python正则表达式提取浮点值,python,regex,floating-point,decimal,Python,Regex,Floating Point,Decimal,我的数据中有带浮点数的字符串,比如 "['0.0'" and '82.00.0' and '82.0\n' 我只想提取浮点数,直到小数点后2/1,就像这样- "['0.0'" and '82.00.0' and '82.0\n' to 0.0, 82.0, 82.0 数据结构是一个大的引用CSV,如: “0.0,82.00.0,…,82.0\n” 我正在迭代这些,以将它们存储到temp tempprices.split(',')) 温度=[] 对于范围内的n(l,len(临时价格)-1):
"['0.0'" and '82.00.0' and '82.0\n'
我只想提取浮点数,直到小数点后2/1,就像这样-
"['0.0'" and '82.00.0' and '82.0\n' to 0.0, 82.0, 82.0
数据结构是一个大的引用CSV,如:
“0.0,82.00.0,…,82.0\n”
我正在迭代这些,以将它们存储到temp
tempprices.split(','))
温度=[]
对于范围内的n(l,len(临时价格)-1):
临时附加(map)(ast.literal\u eval,re.findall(r')(?试试这个:
import re
s = '82.00\n 1.3000 9.1'
result = re.findall(r'\d+\.\d{1,2}', s)
print result
输出:['82.00'、'1.30'、'9.1']有几个问题:
- 您没有将分割块分配给变量(请参见
tempprices.split(',')
)
- 实际上,您必须提取1个值,以便
re.sub
可以工作,但是re.search
更安全
您可以使用以下修复程序:
import re
tempprices = "0.0, 82.00.0,...., 82.0\n"
cells = tempprices.split(',')
temp =[]
for t in cells:
mObj = re.search(r'-?\d+\.\d{1,2}', t)
if mObj:
temp.append(float(mObj.group()))
print(temp)
见
如果每个单元格中都有多个浮点值,则必须将ast.literal\u eval
与re.findall
一起使用:
for t in cells:
temp.extend(map(ast.literal_eval, re.findall(r'-?\d+\.\d{1,2}', t)))
^^^^^^ ^^^^^^^^^^^^^^^^^^^^
看你试过什么?我想会的。只要调整量词。试过这个,没有效果-float(re.sub(r'[^0-9.[0-9][0-9]?],'',price[n])
试过re.findall(r)(?当我使用float(re.findall(r)(?是的,和r'\d+)。\d{1,2}“也将抢占<代码> 1-11和 1:11 谢谢您的时间。这最终奏效了,并且我已经将这些值拆分了,只是存储在同一个变量中。但是谢谢:)很高兴为您工作。如果我的答案证明对您有用的话,请考虑一下投票。