1 回答
TA贡献1826条经验 获得超6个赞
你应该试试这个。此代码使用正则表达式作为一种干净的方式来查找数据。
import pprint
import re
if __name__ == '__main__':
# pattern to ignore line containing alpha or :
ignore_pattern = re.compile(r'[^a-zA-Z:]*[a-zA-Z:]')
# number pattern
number_pattern = re.compile(r'[-.\d]+')
matrix = []
# open the file as readonly
with open('data.txt', 'r') as file_:
# iterator over lines
for line in file_:
# remove \n and spaces at start and end
line = line.strip()
if not ignore_pattern.match(line):
found = number_pattern.findall(line)
if found:
floats = [float(x) for x in found]
matrix.append(floats)
# print matrix in pretty format
pp = pprint.PrettyPrinter()
pp.pprint(matrix)
# access value by [row][column] starting at 0
print(matrix[0][2])
对您的样本数据进行了测试。这是 python 脚本的标准输出:
[[-3.1923, 0.6784, -4.6481, -0.0048, 0.3399, -0.2829, 0.0, 24.0477],
[-3.1827, 0.7048, -4.6257, 0.0017, 0.3435, -0.2855, 0.0, 24.0477],
[-3.1713, 0.7237, -4.5907, 0.0094, 0.3395, -0.2834, 0.0, 24.0477]]
-4.6481
添加回答
举报