我的数据包含带有 float 的字符串,例如
"['0.0'" and '82.00.0' and '82.0\n'
我只想提取 float 直到两位/一位小数点,就像这样-
"['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"
我正在迭代这些以将它们存储到临时变量中
tempprices.split(',')
temp =[]
for n in range(l, len(tempprices)-1):
temp.append(map(ast.literal_eval,re.findall(r'(?<!\S)[+-]?\d+\.\d{1,2}(?!\.*\d)',tempprices[n])))
其中 l 是某个索引值。
我想将这些附加到 temp
像这样[0.0, 82.0, 82.0]
如何实现这一目标?
最佳答案
有几个问题:
- 您没有将分割 block 分配给变量(请参阅
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)
请参阅IDEONE demo
如果每个单元格内可以有多个浮点值,则必须将 ast.literal_eval
与 re.findall
结合使用:
for t in cells:
temp.extend(map(ast.literal_eval, re.findall(r'-?\d+\.\d{1,2}', t)))
^^^^^^ ^^^^^^^^^^^^^^^^^^^^
关于Python正则表达式提取浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37785131/