【问题标题】:Skip reading certain parts in text file python跳过阅读文本文件python中的某些部分
【发布时间】:2020-04-08 10:09:58
【问题描述】:

我有一个如下所示的文件:

Solid ASCII
  facet normal -6.275966e-02 3.134884e-02 -9.975362e-01
    outer loop
      vertex   -4.624000e-01 5.000000e-01 -2.023656e-01
      vertex   -4.624742e-01 4.811628e-01 -2.029529e-01
      vertex   -5.000000e-01 5.000000e-01 -2.000000e-01
    endloop
  endface

我附上了一张照片来解释文本在行中的缩进。我只想阅读数字并填写有效的特定方式,但我管理的方式是:

with open (r'CamaSTL.txt','r+') as infile,\
 open (r'CamaSTL2.txt','w') as outfile:
    for line in infile:
    line = infile.read()
    line = line.replace("facet normal", "")
    line = line.replace("outer loop", "")
    line = line.replace("vertex","")
    line = line.replace("endloop","")
    line = line.replace("endfacet","")
    line = line.replace("endsolid","")
outfile.write(line)

f = open('CamaSTL2.txt','r')
obj1_normal = []
obj1_v1 = []
obj1_v2 = []
obj1_v3 = []
array = []
n = []

for line in f:
    line = line.rstrip()
    if(line):
        for x in line.split():
            array.append(float(x))

i=0

while i < (len(array)):
    n=[array[i],array[i+1],array[i+2]]
    obj1_normal.append(n)
    v1 =[array[i+3], array[i+4], array[i+5]]
    obj1_v1.append(v1)
    v2 =[array[i+6],array[i+7],array[i+8]]
    obj1_v2.append(v2)
    v3 =[array[i+9],array[i+10],array[i+11]]
    obj1_v3.append (v3)
    i +=12

for row in obj1_normal:
    print (row)

删除单词,生成一个新文件,读取新的生成文件并按照我想要的方式放置数字。有没有办法不生成新文件,“跳过”这些单词的阅读,只阅读并附加数字?因为我要用我创建的数组进行算术运算,然后我会想以同样的方式保存(因为我需要在字符串开头的单词)

【问题讨论】:

  • 您可以使用数据格式化文本以显示缩进 - 您不必为此添加图像。
  • 为什么要将数据写入文件只是为了再次读取它?您应该创建包含所有行的新列表。并且您只能添加替换后不为空的行。当您使用for line in infile 时,您不必使用infile.read(),因为您已经在变量line 中有行

标签: python arrays performance function text-files


【解决方案1】:

我认为这种方法可能对你有用:


import re

fp_number_regex = re.compile(r"[-+][0-9]+\.[0-9]+[eE][-+]?[0-9]+")


def filter_floats(lines):
    for line in lines:
        r = re.findall(fp_number_regex, line)
        if r:
            yield r


if __name__ == '__main__':
    with open(r'CamaSTL.txt', 'r') as infile:
        for floats_in_line in filter_floats(infile):
            print(floats_in_line)

输出:

['-6.275966e-02', '-9.975362e-01']
['-4.624000e-01', '-2.023656e-01']
['-4.624742e-01', '-2.029529e-01']
['-5.000000e-01', '-2.000000e-01']

我正在使用正则表达式(我找到here)来匹配字符串中的浮点数。 filter_floats 函数现在每行产生一个在该行中找到的浮点列表。如果没有,则跳过该行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多