簡體   English   中英

我需要遍歷文本文件並從python 3開始並結束滿足條件的位置打印特定文本

[英]I need to iterate over text file and print specific text starting from and end fulfilling condition in python 3

示例txt文件:

vrf X.x.X
hello
!
how are you
!
vrf y.y.y.
hi
!

我想遍歷以上提供的文本並打印從匹配字符串“ vrf ”到匹配字符串“ ! ”的輸出。 根據上述文本,我應該得到輸出

vrf X.x.X
hello
vrf y.y.y.
hi

使用re.findall()函數的解決方案:

import re

with open('lines.txt', 'r') as fh:
    result = re.findall(r'vrf[^!]+(?=!)', fh.read(), re.M)

print(''.join(result))

輸出:

vrf X.x.X
hello
vrf y.y.y.
hi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM