我在.txt文件中读取了以下字符串
{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}
使用lin = lin.strip()
删除'\ n'
然后我将{和}替换为[和]使用
lin = lin.replace ("{", "[")
lin = lin.replace ("}", "]")
我的目标是将lin转换为float 2d数组。所以我做了
my_matrix = np.array(lin, dtype=float)
但是我收到一条错误消息:“ValueError:无法将字符串转换为float:[[1,2,3,0],[1,1,1,2],[0,-1,3,9 ]]“
删除dtype,我得到一个字符串数组。我已经尝试将lin乘以1.0,使用.astype(float)复制lin,但似乎没有任何效果。
答案 0 :(得分:0)
我使用JSON
库来解析文件的内容,然后遍历数组并将每个元素转换为float。但是,整数解决方案可能已足以满足您的需求。那个更快更短。</ p>
import json
fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}'
a = json.loads(fc.replace('{','[').replace('}',']'))
print(a) # a is now array of integers. this might be enough
for linenumber, linecontent in enumerate(a):
for elementnumber, element in enumerate(linecontent):
a[linenumber][elementnumber] = float(element)
print(a) # a is now array of floats
更短的解决方案
import json
fc = '{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}'
a = json.loads(fc.replace('{','[').replace('}',']'))
print(a) # a is now array of integers. this might be enough
a = [[float(c) for c in b] for b in a]
print(a) # a is now array of floats
(适用于python 2和3)
答案 1 :(得分:0)
import numpy as np
readStr = "{{1,2,3,0},{4,5,6,7},{8,-1,9,0}}"
readStr = readStr[2:-2]
# Originally read string is now -> "1,2,3,0},{4,5,6,7},{8,-1,9,0"
line = readStr.split("},{")
# line is now a list object -> ["1,2,3,0", "4,5,6,7", "8,-1,9,0"]
array = []
temp = []
# Now we iterate through 'line', convert each element into a list, and
# then append said list to 'array' on each iteration of 'line'
for string in line:
num_array = string.split(',')
for num in num_array:
temp.append(num)
array.append(temp)
temp = []
# Now with 'array' -> [[1,2,3,0], [4,5,6,7], [8,-1,9,0]]
my_matrix = np.array(array, dtype = float)
# my_matrix = [[1.0, 2.0, 3.0, 0.0]
# [4.0, 5.0, 6.0, 7.0]
# [8.0, -1.0, 9.0, 0.0]]
虽然这可能不是最优雅的解决方案,但我认为它很容易理解,并为您提供您正在寻找的内容。