【问题标题】:Reading in a matrix from textile with Python使用 Python 从纺织品中读取矩阵
【发布时间】:2020-12-30 23:29:23
【问题描述】:

我是 python 新手,正在尝试熟悉它的库功能

假设我有一个文件名 case_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”中提取矩阵,然后将其作为浮点值存储在单独的列表中。有关如何解决此问题的任何提示都会有所帮助。谢谢!

【问题讨论】:

  • case #2 存在缩进错误,您编写它的方式仅在该行已包含 case #1 时才会执行,而且您仅有效地将带有 case #1 的行附加到填充并忽略所有其他行

标签: python list matrix


【解决方案1】:

这行不正确:

stuff.append = ([list(line) for contents in line.split()])

试试这个:

stuff.append = (line.split())

之后,您可以将项目更改为浮动。 (如果您提供一些预期输出的样本,我可以提供帮助)

【讨论】:

  • 谢谢!我对python语法不太熟悉。
【解决方案2】:

我不确定输出应该是什么样子,但这个输出至少会存储所有数据,您可以将其修改为应有的样子

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() != '']
  )

您可能希望排除任何类型的空格,否则您必须为以后的情况创建特殊情况

【讨论】:

  • 谢谢!这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多