在Python中只打印整行的一部分

时间:2016-04-01 16:19:37

标签: python lines

到目前为止我的代码看起来像这样:

g = open("spheretop1.stl", "r")
m = open("morelinestop1.gcode", "w")
searchlines = g.readlines()
file = ""

for i, line in enumerate(searchlines):
    if "outer loop" in line:
        p4 = searchlines[i+1]
        p5 = searchlines[i+2]
        p6 = searchlines[i+3]

文件spheretop1.stl如下所示:

solid spheretop1
   facet normal -4.647520e-002 -9.989174e-001 -2.029244e-003
      outer loop
         vertex 1.930371e+002 1.218346e-001 1.995131e+002
         vertex 1.930244e+002 1.218346e-001 1.997564e+002
         vertex 1.860572e+002 4.871899e-001 1.995131e+002
      endloop
   endfacet
   facet normal 4.650354e-002 -9.989174e-001 -1.217645e-003
      outer loop
         vertex 2.069799e+002 1.218346e-001 2.000000e+002
         vertex 2.069756e+002 1.218346e-001 1.997564e+002
         vertex 2.139428e+002 4.871899e-001 1.995131e+002
      endloop
   endfacet
   facet normal -2.323405e-002 -9.997293e-001 -1.217645e-003
      outer loop
         vertex 1.930244e+002 1.218346e-001 1.997564e+002
         vertex 1.930371e+002 1.218346e-001 1.995131e+002
         vertex 2.000000e+002 0.000000e+000 2.000000e+002
      endloop
   endfacet

我想做的是拥有' p4'是一组数字(浮点数),以顶点行中的第一个数字开头,然后是顶点行中的第二个数字。所以我希望p4看起来像这样:

p4 = (193.0371, 0.1218346).

之后我想要一个p5和一个p6,p5是(193.0244, 0.1218346)而p6是(186.0572, 0.4871899)。现在它给我的是"外循环"下的整条线,我只想从线上获得一个特定的部分。有人知道怎么做吗?感谢。

2 个答案:

答案 0 :(得分:2)

这很简单:

p4 = map(float, searchlines[i+1].split()[1:3])

答案 1 :(得分:0)

list1= p4.split()   # gives  list1= ['vertex','x','y','z']
p4=[float(list[1]),float(list[2])]  # gives you a list of x and y