python提取文本中的字符串到新的txt_从python中的txt文件中提取字符之间的字符串...

一个简单的解决方案如下所示。代码包含许多注释,使您能够理解每一行代码。代码的优点是,它使用with运算符来处理异常并关闭资源(如文件)。#Specify the absolute path to the input file.

file_path = "input.txt"

#Open the file in read mode. with operator is used to take care of try..except..finally block.

with open(file_path, "r") as f:

'''Read the contents of file. Be careful here as this will read the entire file into memory.

If file is too large prefer iterating over file object

'''

content = f.read()

size = len(content)

start =0

while start < size:

# Read the starting index of & after the last ! index.

start = content.find("&",start)

# If found, continue else go to end of contents (this is just to avoid writing if statements.

start = start if start != -1 else size

# Read the starting index of ! after the last $ index.

end = content.find("!", start)

# Again, if found, continue else go to end of contents (this is just to avoid writing if statements.

end = end if end != -1 else size

'''print the contents between $ and ! (excluding both these operators.

If no ! character is found, print till the end of file.

'''

print content[start+1:end]

# Move forward our cursor after the position of ! character.

start = end + 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值