我的代码:
import math
file1=open("g_code.nc","r")
for lines in file1:
lineList=lines.split()
if 'X' and 'Y' in lines:
data=str(math.floor(float((lineList[1][1:]))))+" "+str(math.floor(float((lineList[2][1:]))))+"\n"
file2=open('test.txt','r')
lastline=file2.readlines()[-1]
if data!=lastline:
file2.close()
file2=open("test.txt","a")
file2.write(data)
file2.close()
file1.close()
file2.close()
有人可以更好地解决这个问题,
我想得到X和Y的值,不包括十进制值
请注意,我不希望在连续的行中使用相同的值,但它们可以在几个不同的值之后出现。
输入文件包含以下格式的数据:
G2 X-1.1269 Y-14.4111 I0.0267 J0.027 F60
G2 X-1.1269 Y-14.4111 I0.3267 J0.267 F6
G2 X-3.1269 Y-1.4111 I0.0467 J0.067 F50
G2 X-1.1269 Y-14.4111 I0.067 J0.07 F70
输出应为:
-1 -14
-3 -1
-1 -14
答案 0 :(得分:0)
通常,您使用regular expression来查找号码。通常,您不会为每次写入操作重新打开和关闭文件。这样的事情(未经测试):
import re
numbers = []
def append_if_different(x, y):
if not numbers or (x, y) != numbers[-1]:
numbers.append((x, y))
with open("g_code.nc","r") as inp:
for line in inp:
matches = re.findall(r'[XY]([-+]?\d+)', line)
if len(matches) == 2:
append_if_different(int(matches[0]), int(matches[1]))
with open("test.txt", "w") as outp:
for xy in numbers:
outp.write("{} {}\n".format(*xy))