我在用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))
我想我没有理解线和多行字符串之间的区别。我真的很感谢你的帮助!你知道吗
提前谢谢你,亚瑟
如果字符串包含换行符
\n
,则它有多行。你知道吗可以将文件视为包含换行符的一个长字符串:
也可以将其视为一系列行:
如果有多行字符串,可以将其拆分为行列表:
如果要逐行处理文件,则以下所有方法都是等效的(如果效率不高,则有效):
编辑现在问题的解决方案:
这将把匹配
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)
)作为子字符串搜索而不是单词匹配,我也不知道这是否是您的意图。你知道吗编辑2回复评论:
相关问题 更多 >
编程相关推荐