[英]Python extract text 4 lines after match
所以我有一個文本文件,我需要在特定標題后的4行中提取一行文本。
即:
標題
1號線
2號線
3號線
要提取的線
我一直在尋找一種簡單的方法來進行操作,但是我對python的了解太有限,無法將我發現的任何內容應用於此特定情況。 謝謝!
找到標題,然后僅取下四行,最后一行將是您想要的。
from itertools import islice
with open("words.txt") as f:
for line in f:
if line.rstrip() == "Heading":
print(list(islice(f, 4))[-1])
break
line to be extracted
或使用linecache在Heading
行之后四行獲取行:
from linecache import getline
with open("words.txt") as f:
for ind, line in enumerate(f,1):
if line.rstrip() == "Heading":
print(getline(f.name, ind + 4))
break
line to be extracted
如果您有多行,請不要中斷。
from linecache import getline
with open("words.txt") as f:
for ind, line in enumerate(f,1):
if line.rstrip() == "Heading":
print(getline(f.name, ind + 4))
line to be extracted
other line to be extracted
with open('file.txt') as f:
data = f.read().split('\n')
if 'Heading' in data:
my_line = data[data.index('Heading') + 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.