如何解决在文档行中查找字符串,然后从前一行的值中获取值
我正在读取与此类似的文本文件:
...
#9 1.11 2.22
#10 3.33 4.44
#11 5.55 6.66
#12 7.77 8.88
#13 6.999 0.189
...
某些行可能存在或不存在的地方,例如从#13
行开始。
我想做的就是测试这种情况下的文本文件,如果经过验证,则取先前几行中的值(而不仅仅是前一行),说#9:
for test in open('example.txt'):
line = test.split()
if test.find("#13") != -1:
collect.append(line[1]) # <-- here should be the value from the line starting with "#9"
在python中最合适的方法是什么?
解决方法
我不知道为什么在示例中#13
将需要带有#9
的行,但是根据您的描述,您可以使用一个额外的变量来跟踪上一行:
prevline = []
for test in open('example.txt'):
line = test.split()
if test.find("#13") != -1:
collect.append(prevline[1])
prevline = line
,
collect = []
with open("example.txt") as file:
prevLine = file[0]
for line in file[1:]:
if "#13" in line:
collect.append(prevLine.split(" ")[1:])
prevLine = line
这将打开文件并读取所有行。找到包含"#13"
的行时,会将所有数字添加到列表collect
中,该列表出现在前一行的标签(#+一个数字)之后。如果"#13"
不在该行中,它将把该行存储为前一行。
鉴于文件很小(大约20行),只需使用r
读取整个文件:
readlines()
或with open(filename,'rt') as f:
lines = f.readlines() # this keeps the \n on each line
和read()
:
splitlines()
然后做测试,返回相应的行:
with open(filename,'rt') as f:
lines = f.read().splitlines() # this strips trailing whitespace on each line
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。