[英]how to extract a certain number of lines from somewhere within a file
我有一個輸入文件,看起來像這樣:
#nP 4
#mP 0.0262
#mH 10
#HP various info:
14 H 0.026
19 P 0.054
20 H 0.012
512 H 0.005
#xP
#kP
99
89
90
我想從第5行開始提取4行(因為第一行中的np = 4),因此輸出將如下所示:
14 H 0.026
19 P 0.054
20 H 0.012
512 H 0.005
我試過這個:
import sys
head = sys.stdin.readline()
head = head.strip()
head = head.split('\t')
cntHetPos = int(head[1])
if "#HP" in sys.stdin.readlines():
lines = sys.stdin.readlines()[0:cntHetPos]
print lines
但它不打印出行,也沒有給出錯誤信息。 我基於我在此處找到的先前答案: 基於第2行讀取文件或跳過標題行想法?
readlines()
在您第一次調用它時返回所有行的列表,但第二次,它是空的,因為所有行都已被讀取和使用。 將它們存儲在變量中:
lines = sys.stdin.readlines()
把它放在頂部,因為你不妨用它來讀取你的head
變量:
head = lines[0]
另一個問題是您需要遍歷所有行以查找#HP
令牌,並且您需要跟蹤行號以便正確切片列表:
for i, line in enumerate(lines):
if "#HP" in line:
lines = lines[i+1 : i+1+cntHetPos]
最后,如果要打印行而不是格式化列表,則需要加入它們(請注意,行尾字符已經在那里):
print ''.join(lines),
而且,為了更好的衡量,我們可以在找到合適的線后立即停止,因此我們會在print
后立即break
。
總結一下:
import sys
lines = sys.stdin.readlines()
head = lines[0]
head = head.strip()
head = head.split('\t')
cntHetPos = int(head[1])
for i, line in enumerate(lines):
if "#HP" in line:
lines = lines[i+1 : i+1+cntHetPos]
print ''.join(lines),
break
這是一個非常丑陋的匹配模式,但它可能適合您的需求;
/#nP.*?#HP.*?$.*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+)/gsm
它會將您要抓取的4條線的結果分組並將它們分組。 你甚至可以對結果進行分組,這樣你就可以分別立即得到14 H 0.026
。 就像是;
(\d+) +(\w) +([\d\.]+)
例
import re
string = '''#nP 4
#mP 0.0262
#mH 10
#HP various info:
14 H 0.026
19 P 0.054
20 H 0.012
512 H 0.005'''
result = re.findall('#nP.*?#HP.*?$.*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+).*?(\d+ +\w +[\d\.]+)', string, re.S | re.M)
print(result)
產量
[('14 H 0.026', '19 P 0.054', '20 H 0.012', '512 H 0.005')]
也許是這樣的:
from itertools import islice
with open('yourfile') as fin:
count = int(next(fin).split()[1])
non_comments = (line for line in fin if not line.startswith('#'))
print list(islice(non_comments, None, count))
# ['14 H 0.026\n', '19 P 0.054\n', '20 H 0.012\n', '512 H 0.005\n']
linecache模塊專為從文件中有效讀取行而定制:
linecache模塊允許從任何文件獲取任何行,同時嘗試使用緩存在內部進行優化,這是從單個文件中讀取許多行的常見情況。 跟蹤模塊使用它來檢索包含在格式化回溯中的源代碼行。
假設文本文件名為blah
,文件數據從第五行開始:
#!/usr/bin/python
import linecache
starting_line_number = 5
number_of_lines = int(linecache.getline('blah',1).split()[1])
for line_num in range(starting_line_number, starting_line_number+number_of_lines):
print linecache.getline('blah',line_num),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.