[英]Python - convert list of string to float - square braces and decimal point causing problems
我有一个包含较小数据集的文本文件(取自 csv 文件),如下所示 -
2020-05-24T10:44:37.613168#[ 0. 0. -0.06210425 0. ]
2020-05-24T10:44:37.302214#[1. 1. 0. 0.]
2020-05-24T10:44:36.192222#[0. 0. 0. 0.]
然后使用它从中读取
data = f.readlines()
for row in data:
img_id, label = row.strip("\n").split("#")
其中 label 是一个字符串列表,看起来像
[ 0. 0. -0.24604772 0. ]
[ 0. 0. -0.24604772 0. ]
[1. 1. 0. 0.]
我想将每个字符串元素转换为浮点数。 但是,方括号[]
和小数点.
阻止我转换。
到目前为止尝试过 -
删除[]
所以 - label = label[1:-1]
但我稍后需要它们作为数组。 然后执行此print([list(map(float, i.split())) for i in label])
导致错误ValueError: could not convert string to float: '.'
使用ast.literal_eval
。 label = ast.literal_eval(row.strip("\n").split("#"))
。 获取ValueError: malformed node or string: ['2020-05-24T10:57:52.882241 [0. 0. 0. 0.]']
ValueError: malformed node or string: ['2020-05-24T10:57:52.882241 [0. 0. 0. 0.]']
参考
无法使用 float() 将字符串列表转换为 python 中的浮点列表
所以,
谢谢你。 任何帮助将不胜感激。 请帮忙。
for row in data:
img_id, label = row.strip("\n").split("#")
# >>>[ 0. 0. -0.24604772 0. ]
label = label[1:-1] # Cuts the first and last letter
# >>> 0. 0. -0.24604772 0.
label = label.strip() # Remove all spaces before and after label
# >>>0. 0. -0.24604772 0.
labelElements = label.split() # Cuts the string on every space(s)
# >>>["0.", "0.", "-0.24604772", "0."]
labelFloats = []
for L in labelElements:
labelFloats.append(float(L)) # for example: "1." -> 1.0
顺便一提:
变量 [label] 没有行列表(您称其为“字符串列表”),它只有一行:
# label = [ 0. 0. -0.24604772 0. ]
对于每一行,用line[1:-1]
修剪第一个和最后一个字符,用.split()
用空格分隔,用float()
解析每个浮点数。
line = "[ 0. 0. -0.24604772 0. ]"
floats = [float(item) for item in line[1:-1].split()]
print(floats)
>>> [0.0, 0.0, -0.24604772, 0.0]
我想鉴于你的情况,我想我会用正则表达式 go 来提取所需的数字。 我会做如下事情:
import re
f = open('your_file.txt')
lines = f.read().splitlines()
f.close()
floats = []
for line in lines:
img_id, label = line.split("#")
floats.append([*map(float, re.findall('-?[\d]+\.?[\d]*', label))])
打印floats
输出:
[[0.0, 0.0, -0.06210425, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.