用python读取txt文件里的数字并求和_“值错误:使用python从.txt文件的字符串中提取数字时,迭代和读取方法混合会丢失数据”消息...

I have a program that grabs numbers from a .txt file and puts it into an array. The problem is that the numbers are not isolated or ordered. The .txt file looks like this:

G40 Z=10

A=30 X10 Y50

A=30 X40 Y15

A=50 X39 Y14

G40 Z=11

A=30 X10 Y50

A=30 X40 Y15

A=50 X39 Y14

The output should be a new .txt file that has the following array format

X Y Z

10 50 10

40 15 10

39 14 10

10 50 11

40 15 11

39 14 11

This is what I have done so far, although I'm not sure how to write my output to a new file...

inputfile = open('circletest1.gcode' , 'r')

def find_between( s, first, last ):

try:

start = s.index( first ) + len( first )

end = s.index( last, start )

return s[start:end]

except ValueError:

return ""

for i in range(203): inputfile.next() # skip first 203 lines

while True:

my_text = inputfile.readline()

z = find_between(my_text, "Z =", " ")

x = find_between(my_text, "X", " ")

y = find_between(my_text, "Y", " ")

print(x ," ", y, " ", z)

if not my_text:break

inputfile.close()

For a while I was receiving indentation errors, but I believe that I have fixed that problem. Now the error message that I am getting is "Value error: Mixing iteration and read methods would lose data".

I am not sure where to go from here, nor am I sure how to import my results into another separate new txt file.

Also, in my code, is there a way to preserve the z value outside of the loop until a new z value is assigned?

解决方案

If I understand correctly, you want to combine the Z value from the lines that start with G with the X and Y values from the following lines (until the next G line).

If so, I'd use a single loop, printing only on the lines that start with A and just saving the new Z value on the lines that start with G. I'd do the line parsing with regex, but you could use simple string manipulation if you wanted to (I'd split and then skip the first letter or letters of the relevant items).

import itertools

import re

z = None

with open('circletest1.gcode') as input_file:

for line in itertools.islice(203, None): # islice to skip the first 203 lines

if line.startswith("G"):

z = re.search(r"Z=(\d+)", line).group(1)

elif line.startswith("A"):

x, y = re.search(r"X(\d+) Y(\d+)", line).groups()

print(x, y, z)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值