Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式提取浮点值_Python_Regex_Floating Point_Decimal - Fatal编程技术网

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谢谢您的时间。这最终奏效了,并且我已经将这些值拆分了,只是存储在同一个变量中。但是谢谢:)很高兴为您工作。如果我的答案证明对您有用的话,请考虑一下投票。