我在使用Python编写程序时遇到了一些困难。我希望程序读取一组字符之间的行,颠倒行的顺序,然后将它们写入一个新文件。输入是:
AN10 G17 G21 G90
N20 '2014_12_08_Banding_Test_4
N30 M3 S1B
N40G00X0.000Y0.000Z17.000
N50 G00X0.001Y0.001Z17.000
N60 G01Z0.000F3900.0
N70 G01X0.251
N80 G01X149.999
N90 G01Y0.251
N100 G01X149.749
N110 G01X149.499Z-8.169
N120 G01X148.249Z-8.173
N130 G01X146.999Z-8.183
N140 G01X145.499Z-8.201
...
N3140 G01Y0.501
到目前为止,我的代码是:
with open('Source.nc') as infile, open('Output.nc', 'w') as outfile:
copy = False
strings_A = ("G01Y", ".251")
strings_B = ("G01Y", ".501")
content = infile.readlines()
for lines in content:
lines.splitlines(1)
if all(x in lines for x in strings_A):
copy = True
elif all(x in lines for x in strings_B):
copy = False
elif copy:
outfile.writelines(reversed(lines))
我认为我无法理解线条和多线条字符串之间的区别。我真的很感激这里的一些帮助!
先谢谢你,Arthur
答案 0 :(得分:2)
如果字符串包含换行符\n
,则该字符串有多行。
您可以将文件视为包含换行符的一个长字符串:
s = infile.read()
或者您可以将其视为一系列行:
lines = infile.readlines()
如果您有多行字符串,可以将其拆分为行列表:
lines = s.splitlines(False)
# which is basically a special form of:
lines = s.split('\n')
如果您想逐行处理文件,则以下所有方法都是等效的(如果效率不高则有效):
with open(filename, 'r') as f:
s = f.read()
lines = s.splitlines()
for line in lines:
# do something
pass
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
# do something
pass
# this last option is the most pythonic one,
# it uses the fact that any file object can be treated as a list of lines
with open(filename, 'r') as f
for line in f:
# do something
pass
编辑现在解决您的问题:
with open('Source.nc') as infile, open('Output.nc', 'w') as outfile:
copy = False
strings_A = ("G01Y", ".251")
strings_B = ("G01Y", ".501")
target_lines = []
for line in infile:
if copy and all(x in line for x in strings_B):
outfile.writelines(reversed(target_lines))
break
if copy:
target_lines.append(line)
if all(x in line for x in strings_A):
copy = True
这会将匹配all(x in line for x in strings_A)
的行与匹配all(x in line for x in strings_B)
的行之间的所有行以相反的顺序复制到outfile中。识别行不包含在输出中(我希望这是意图)。
if
条款的顺序是故意实现的。
另请注意,您使用的身份验证测试(all(x in line for x in strings_A)
),作为子字符串搜索而不是单词匹配,我再也不知道这是否是您的意图。
EDIT2 回复评论:
with open('Source.nc') as infile, open('Output.nc', 'w') as outfile:
strings_A = ("G01Y", ".251")
strings_B = ("G01Y", ".501")
do_reverse = False
lines_to_reverse = []
for line in infile:
if all(x in line for x in strings_B):
do_reverse = False
outfile.writelines(reversed(lines_to_reverse))
outfile.writeline(line)
continue
if do_reverse:
lines_to_reverse.append(line)
continue
else:
outfile.writeline(line)
if all(x in line for x in strings_A):
do_reverse = True
lines_to_reverse = []