Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

How to refer a certain place in a line in Python

I have this little piece of code:

g = open("spheretop1.stl", "r")
m = open("morelinestop1.gcode", "w")
searchlines = g.readlines()
file = ""
for i, line in enumerate(searchlines):
    if X1 in line and Y1 in line:
        m.write("start" + "
")

with X1 = '206.9799' and Y1 = '0.1218346'

the line this file refers to looks like this:

  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

I basically only want the file to write "start" + " " when the X1 and Y1 are in the same line AND are the first two variables in that line, as in the 3rd line above. So what I want to do is find X1 in the line at position x (17 spaces from left) and Y1 in the line at position y (31 spaces from left). Hope that its clear :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use regular expressions. Live example.

import re

X1 = 206.9799
Y1 = 0.1218346

for i, line in enumerate(lines):
    r = re.match(r'^s*vertex (d+.d+e[-+]d+) (d+.d+e[-+]d+) d+.d+e[-+]d+s*$', line)
    if r and X1 == float(r.group(1)) and Y1 == float(r.group(2)):
        m.write("start" + "
") 

Be aware that comparing floats can be imprecise. You have to decide how much imprecision you're willing to accept when comparing values. You can use a function like this to compare two floats within a certain amount of precision.

def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
     return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...