我有一个看起来像这样的文件:
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)
删除单词,生成一个新文件,读取新的生成文件,然后按我想要的方式放置数字。有没有办法不生成新文件,“跳过”这些单词的阅读,而只阅读并附加数字?因为我要对创建的数组进行算术运算,然后我将以相同的方式保存(因为需要,所以在字符串的开头加上了字)
答案 0 :(得分: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
函数会产生在此行中找到的浮点列表。如果没有,则跳过该行。