如何解决使用“startswith”和“next”命令从文件中选择行
我有一个文件,我想从中创建一个列表(“timestep”),其中的数字出现在每行“ITEM:timestep”之后,所以:
timestep = [253400,253500,.. etc]
这是我拥有的文件示例:
ITEM: timestep
253400
ITEM: NUMBER OF ATOMS
378
ITEM: Box BOUNDS pp pp pp
-2.6943709180241954e-01 5.6240920636804063e+01
-2.8194230631882372e-01 5.8851195163321044e+01
-2.7398090193568775e-01 5.7189372326936599e+01
ITEM: ATOMS id type q x y z
16865 3 0 28.8028 1.81293 26.876
16866 2 0 27.6753 2.22199 27.8362
16867 2 0 26.8715 1.04115 28.4178
16868 2 0 25.7503 1.42602 29.4002
16869 2 0 24.8716 0.25569 29.8897
16870 3 0 23.7129 0.593415 30.8357
16871 3 0 11.9253 -0.270359 31.7252
ITEM: timestep
253500
ITEM: NUMBER OF ATOMS
378
ITEM: Box BOUNDS pp pp pp
-2.6943709180241954e-01 5.6240920636804063e+01
-2.8194230631882372e-01 5.8851195163321044e+01
-2.7398090193568775e-01 5.7189372326936599e+01
ITEM: ATOMS id type q x y z
16865 3 0 28.8028 1.81293 26.876
16866 2 0 27.6753 2.22199 27.8362
16867 2 0 26.8715 1.04115 28.4178
16868 2 0 25.7503 1.42602 29.4002
16869 2 0 24.8716 0.25569 29.8897
16870 3 0 23.7129 0.593415 30.8357
16871 3 0 11.9253 -0.270359 31.7252
为此,我尝试同时使用“startswith”和“next”命令,但没有奏效。还有其他方法吗?我还发送了我正在尝试使用的代码:
timestep = []
with open(file,'r') as f:
lines = f.readlines()
for line in lines:
line = line.split()
if line[0].startswith("ITEM: timestep"):
timestep.append(next(line))
print(timestep)
解决方法
逻辑是决定是否将当前的line
附加到timestep
。因此,您需要的是一个变量,当该变量为 TRUE 时,它会告诉您附加当前的 line
。
timestep = []
append_to_list = False # decision variable
with open(file,'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip() # remove "\n" from line
if line.startswith("ITEM"):
# Update add_to_list
if line == 'ITEM: TIMESTEP':
append_to_list = True
else:
append_to_list = False
else:
# append to list if line doesn't start with "ITEM" and append_to_list is TRUE
if append_to_list:
timestep.append(line)
print(timestep)
输出:
['253400','253500']
,
所以你的代码的问题很微妙。您有一个可迭代的列表 lines
,但不能在列表上调用 next
。
相反,把它变成一个显式迭代器,你应该没问题
timestep = []
with open(file,'r') as f:
lines = f.readlines()
lines_iter = iter(lines)
for line in lines_iter:
line = line.strip() # removes the newline
if line.startswith("ITEM: TIMESTEP"):
timestep.append(next(lines_iter,None)) # the second argument here prevents errors
# when ITEM: TIMESTEP appears as the
# last line in the file
print(timestep)
我也不确定你为什么包含 line.split
,这似乎是不正确的(在任何情况下 line.split()[0].startswith('ITEM: TIMESTEP')
永远不可能是真的,因为拆分会将 ITEM:
和 {{ 1}} 到结果列表的单独元素中。)
要获得更可靠的答案,请考虑根据行以 TIMESTEP
开头的时间对数据进行分组。
ITEM
这将让您传入整个文件,并为每个 def process_file(f):
ITEM_MARKER = 'ITEM: '
item_title = '(none)'
values = []
for line in f:
if line.startswith(ITEM_MARKER):
if values:
yield (item_title,values)
item_title = line[len(ITEM_MARKER):].strip() # strip off the marker
values = []
else:
values.append(line.strip())
if values:
yield (item_title,values)
组懒惰地生成一组值。然后你可以以某种合理的方式进行聚合。
ITEM: <whatever>
,
首先 - 我不喜欢这个,因为它不能扩展。您只能很好地获得紧随其后的第一行,其他任何事情都只是呃......
但是你问了,所以...... import seaborn as sns
sns.lineplot(data=data,x='date',y='value',hue='type')
将在行上创建一个迭代器并使用它来保持位置。您无权访问该迭代器,因此 import matplotlib.pyplot as plt
fig,ax = plt.subplots()
for label,group in data.groupby('type'):
group.plot(x='date',label=label,ax=ax)
不会是您期望的下一个元素。但是您可以制作自己的迭代器并使用它:
for x in lines
但是,如果您想扩展它... next
不是迭代这样的文件的好方法。您想知道下一行/上一行中的内容。我建议使用 lines_iter = iter(lines)
for line in lines_iter:
# whatever was here
timestep.append(next(line_iter))
:
for
通过这种方式,您可以将其扩展为不同类型的可变长度项目。
,您可以使用 enumerate 来帮助进行索引引用。我们可以检查字符串 ITEM: TIMESTEP
是否在前一行,然后将整数添加到我们的时间步长列表中。
timestep = []
with open('example.txt','r') as f:
lines = f.readlines()
for i,line in enumerate(lines):
if "ITEM: TIMESTEP" in lines[i-1]:
timestep.append(int(line.strip()))
print(timestep)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。