Python 在文本文件中的字符串之间提取信息
我有一个结构如下的数据文件:Python 在文本文件中的字符串之间提取信息,python,string,text,extract,Python,String,Text,Extract,我有一个结构如下的数据文件: handle:trial1 key_left:3172 key_up: xcoords:12,12,12,15........ ycoords:200,200,206,210,210...... t:20,140,270,390..... goalx:2 goaly:12 fractal:images/file.png seen:true pauseTimes: fractal:images/file2.png seen:False pau
handle:trial1
key_left:3172
key_up:
xcoords:12,12,12,15........
ycoords:200,200,206,210,210......
t:20,140,270,390.....
goalx:2
goaly:12
fractal:images/file.png
seen:true
pauseTimes:
fractal:images/file2.png
seen:False
pauseTimes:
...
...
我只想提取goaly
行之后直到pauseTimes
行的信息。如果我知道所有试验的goaly
值,我可以指定该行并提取goaly:
和pauseTimes
之间的数据,但我不会提前知道任何goaly
的值,因为它们是动态生成的
我如何使用字符串
“goaly”
来标识该行,然后提取所有后续行,直到暂停时间
行?无论是否关心该行,都可以使用状态变量进行循环和跟踪。我喜欢使用生成器跟踪解析状态,使其与处理代码分离。以下是生成器的示例:
extracting = False
with open('path/to/file') as f:
for line in f:
if line.startswith('goaly:'):
extracting = True
if extracting:
# I'm not really sure how you want to receive this
# data, but that's what would go here....
if line.startswith('pauseTimes:'):
extracting = False
def parse(infile):
returning = False
trial = None
for line in infile:
line = line.rstrip()
if not line:
continue
if line.startswith('handle:'):
trial = line[len('handle:'):]
if line.startswith('goaly:'):
returning = True
elif line.startswith('pauseTimes:'):
returning = False
if returning:
yield trial, line
下面是您将如何使用它:
for trial, line in parse(open('test.txt', 'r')):
print(trial, line)
具有跟踪您参加的试用的附加功能。您尝试过什么吗?在python中,这应该是一项相当常规的任务。如果您发布一个代码示例,我们可以帮助您解决问题。我确实使用了line.strip(),但这需要(我相信)行的确切内容。使用line.startswith应该可以做到这一点。如果我有其他问题,我将在自定义代码后恢复!谢谢。这很有效,谢谢,非常有启发性,作为一个初学者,我很欣赏。还有一个noob问题-如何将打印输出(试用版,行)保存到变量?使用另一个循环?提前感谢。我的初学者尝试是new_data=parse(infle),但那不起作用。