我有一个混合浮点数作为字符串表示列表的 TXT 文件。当我将每个元素转换为浮点数列表时,负科学值不会出现在新列表中。例如,当我有以下值时:
line1 : [119. 114. 67. 117.706474 113.051278 69.933043]
line2 : [ 1.20000000e+02 0.00000000e+00 6.70000000e+01 1.20217686e+02
line3 : -8.89000000e-04 7.03216110e+01]
我的输出是
line1 : [119. 114. 67. 117.706474 113.051278 69.933043]
line2 : [ 1.20000000e+02 0.00000000e+00 6.70000000e+01 1.20217686e+02]
正如你所看到的输出不显示从负值开始的数字。
input_file = open('file.txt', 'r')
output_file = "new_file.txt"
lines = input_file.readlines()
#print(lines)
with open(output_file, "w") as filehandle:
for line in lines:
transformed_points = line.split('\n')
a = transformed_points[0]
#print(transformed_points[0].strip().replace('. ',','))
a = a.replace('[', '').replace(']', '')
floats = [float(x) for x in a.split()]
filehandle.write(str(floats[3:5])+' \n')
这不是最干净的实现,但它可以工作。
您可以将其用作处理原始数据行的函数。
input_file = open('file.txt', 'r')
output = 'new_file.txt'
lines = input_file.read()
# print(lines)
add = False
newlines=[]
for char in lines:
if char == '[':
add=True
line = []
continue
if char ==']':
add=False
newlines.append(''.join(line))
continue
if char == '\n': continue
if add == True: line.append(char)
newlines_float = [list(map(float,line.split())) for line in newlines]
for i in newlines_float:
print(i)
input_file.close()
# the output of this is a nested list with float numbers.
# You can use f-string formatting to properly output this as you wish.
此输出
[119.0, 114.0, 67.0, 117.706474, 113.051278, 69.933043]
[120.0, 0.0, 67.0, 120.217686, -0.000889, 70.321611]
我认为 input_files 的示例字符串由 3 行组成
line1 : '[119. 114. 67. 117.706474 113.051278 69.933043]'
line2 : '[ 1.20000000e+02 0.00000000e+00 6.70000000e+01 1.20217686e+02'
line3 : '-8.89000000e-04 7.03216110e+01]'
所以如果你使用
for line in lines:
示例 line3 与原始线(line2)分离
请检查此
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(41条)