提取文本文件中两个字符串之间的值 [英] Extract Values between two strings in a text file
本文介绍了提取文本文件中两个字符串之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含以下内容的文本文件
Lets say I have a Text file with the below content
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
Start
hgjkkl
dfghjjk
fghjjj
Start
Good Evening
Good
End
我编写了以下代码:
infile = open('test.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
elif line.strip() == "End":
copy = False
elif copy:
outfile.write(line)
我的结果在文件外:
Good Morning
Hello World
hgjkkl
dfghjjk
fghjjj
Good Evening
Good
我的问题是我只想在开始和结束之间取数据,而不要在开始和开始或结束和结束之间取数据
My problem is I want to take just the data between start and end but not between start and start or End and End
推荐答案
大问题!这是一个桶问题,每个起点都需要一个终点.
Great problem! This is a bucket problem where each start needs an end.
之所以得到结果,是因为有两个连续的开始".
The reason why you got the result is because there are two consecutive 'Start'.
最好将信息存储到某个地方,直到触发"End"为止.
It's best to store the information somewhere until 'End' is triggered.
infile = open('scores.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
bucket = []
copy = True
elif line.strip() == "End":
for strings in bucket:
outfile.write( strings + '\n')
copy = False
elif copy:
bucket.append(line.strip())
这篇关于提取文本文件中两个字符串之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文