首页 > 解决方案 > 使用生成器从文件构造列表

问题描述

我正在编写一个脚本,需要从大文件中的特定位置读取矩阵。文件中感兴趣的位置如下所示:

VOLUME and BASIS-vectors are now :
 -----------------------------------------------------------------------------
  energy-cutoff  :      500.00
  volume of cell :      478.32
      direct lattice vectors                 reciprocal lattice vectors
     7.831488362  0.000000000  0.000000000     0.127689649  0.000000000  0.000000000
     0.000000000  7.773615667  0.000000000     0.000000000  0.128640268  0.000000000
     0.000000000  0.000000000  7.856881120     0.000000000  0.000000000  0.127276967

我需要倒数格向量。有很多方法可以获取这些数字,但文件有数千行,所以我不能(不应该)将整个内容存储为行列表。该限制使提取我想要的数据变得更加困难。这是我到目前为止所拥有的:

with open('OUTCAR','r') as read_outcar:
    for line in read_outcar:
        if 'VOLUME' in line:
            for i in range(5):  #skip to line with data
                next(read_outcar)
            buffer = line.split()
            x = [float(buffer(i+3)) for i in buffer]
            next(read_outcar)
            buffer = line.split()
            y = [float(buffer(i+3)) for i in buffer]
            next(read_outcar)
            buffer = line.split()
            z = [float(buffer(i+3)) for i in buffer]
            break

这里有两个问题:

1.)我不确定我对“下一个”的使用是否正确/合适,但我不知道如何从文件中获取与迭代器关联的当前行之后的行

2.) 我的发电机不工作。解释器引发类型错误,因为我显然试图连接 str 和 int 类型。我想要的是倒数格矩阵中每一行的浮点数列表。

对此的任何帮助将不胜感激。提前致谢。

标签: python

解决方案


代码有几个问题:

  • next返回迭代器的下一项,并且由于您拆分,line您应该通过以下方式捕获它line = next(read_outcat)
  • 然后缓冲区是一个列表,它通过方括号索引,即buffer[...]。但是,由于您似乎对最后三个元素感兴趣,您可以通过buffer[-3:].

这里修改后的代码:

with open('OUTCAR') as read_outcar:
    for line in read_outcar:
        if 'VOLUME' in line:
            for i in range(5):  #skip to line with data
                line = next(read_outcar)
            buffer = line.split()
            x = [float(b) for b in buffer[-3:]]
            line = next(read_outcar)
            buffer = line.split()
            y = [float(b) for b in buffer[-3:]]
            line = next(read_outcar)
            buffer = line.split()
            z = [float(b) for b in buffer[-3:]]
            print(f'x = {x}, y = {y}, z = {z}')
            break

推荐阅读