我是python的新手,正在尝试熟悉它的库功能
假设我有一个名为cases_test.txt的文件,其中的内容如下:
cases: 2
matrix size: 5 x 5
case #1 matrix:
x. v. t. u. w.
x 0.5 0.6 1.2 2.0 1.3
v 0.7 0.8 1.0 3.0 0.3
t 0.4 0.3 0.7 0.1 0.6
u 1.2 3.2 0.2 2.9 1.9
w 0.2 0.5 0.9 0.3 1.7
case #2 matrix:
x. v. t. u. w.
x 1.8 0.9 0.0 1.3 1.4
v 0.5 0.5 2.3 3.3 0.1
t 1.3 0.3 0.7 0.1 0.2
u 1.7 3.9 2.5 1.2 1.3
w 0.1 0.2 0.9 0.3 1.1
variables: 5到目前为止,我有以下几点:
def read_file(text_File):
file = open(text_File, "r") #open file for reading
stuff = [] #empty list to hold contents after "case #1 matrix"
for line in file:
#For in is used to loop through lines in a file
if 'case #1 matrix:' in line:
print("At matrix one\n")
##Reached matrix one
stuff.append = ([list(line) for contents in line.split()])
if 'case #2 matrix:' in line:
print("At matrix two\n")
##Breaks when the next matrix is encountered
break
print(stuff)
print("Contents in list stuff printed")
return stuff最后,我想从我的列表"stuff“中提取矩阵,然后将其存储为一个单独的列表中的浮点值。任何关于如何实现这一点的提示都会有所帮助。谢谢!
发布于 2020-12-31 07:38:53
这一行不正确:
stuff.append = ([list(line) for contents in line.split()])试着这样做:
stuff.append = (line.split())在此之后,您可以将项更改为浮动。(如果您提供一些预期输出的示例,我可以提供帮助)
发布于 2020-12-31 07:45:23
我不确定输出到底应该是什么样子,但这个输出至少会存储所有数据,您可以将其修改为应该是什么样子
def read_file(text_File):
stuff = {}
cur_matrix = ''
with open(text_File) as fp:
for line in fp.readlines():
if 'case #1 matrix:' in line:
cur_matrix = 1
print("At matrix one\n")
continue
if 'case #2 matrix:' in line:
cur_matrix = 2
print("At matrix two\n")
continue
if cur_matrix != '':
if line.strip() != '':
stuff.setdefault(cur_matrix, []).append(
[x for x in line.split() if x.strip() != '']
)
print(stuff)
print("Contents in list stuff printed")
return stuff
read_file('file.txt')我逐行解析文件,您必须记住在哪种情况下将其存储在正确的字典值中。
也用于解析
stuff.setdefault(cur_matrix, []).append(
[x for x in line.split() if x.strip() != '']
)您可能希望排除任何类型的空格,否则您必须为以后的空格创建特殊情况
https://stackoverflow.com/questions/65514830
复制相似问题