gpt4 book ai didi

python - 反转列表中行的顺序

转载 作者:行者123 更新时间:2023-12-01 04:55:40 27 4
gpt4 key购买 nike

我在用 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,则该字符串有多行。

您可以将文件视为包含换行符的长字符串:

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) 匹配的行之间的所有行 code> 以相反的顺序进入输出文件。识别行不包含在输出中(我希望这是意图)。if 子句的顺序是为了实现这一目标而特意设计的。

还要注意,您使用的识别测试 (all(x in line for x in strings_A)) 是作为子字符串搜索而不是单词匹配,同样,我不知道是否可以是你的意图。

编辑2回复评论:

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 = []

关于python - 反转列表中行的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27443697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com