python提取txt中的字符串数据_从python中的txt文件中提取字符之间的字符串

1586010002-jmsa.png

I have a txt file that I want python to read, and from which I want python to extract a string specifically between two characters. Here is an example:

Line a

Line b

Line c

&TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST !

Line d

Line e

What I want is python to read the lines and when it encounters "&" I want it to start printing the lines (including the line with "$") up untill it encounters "!"

Any suggestions?

解决方案

This works:

data=[]

flag=False

with open('/tmp/test.txt','r') as f:

for line in f:

if line.startswith('&'):

flag=True

if flag:

data.append(line)

if line.strip().endswith('!'):

flag=False

print ''.join(data)

If you file is small enough that reading it all into memory is not an issue, and there is no ambiguity in & or ! as the start and end of the string you want, this is easier:

with open('/tmp/test.txt','r') as f:

data=''.join(f.readlines())

print data[data.index('&'):data.index('!')+1]

Or, if you want to read the whole file in but only use & and ! if they are are at the beginning and end of the lines respectively, you can use a regex:

import re

with open('/tmp/test.txt','r') as f:

data=''.join(f.readlines())

m=re.search(r'^(&.*!)\s*?\n',data,re.S | re.M)

if m: print m.group(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值