輸入:
ID aa
AA Homo sapiens
DR ac
BB ad
FT ae
//
ID ba
AA mouse
DR bc
BB bd
FT be
//
ID ca
AA Homo sapiens
DR cc
BB cd
FT ce
//
預期輸出:
DR ac
FT ae
//
DR cc
FT ce
//
代碼:
word = 'Homo sapiens'
with open(input_file, 'r') as txtin, open(output_file, 'w') as txtout:
for block in txtin.read().split('//\n'): # reading a file in blocks
if word in block: # extracted block containing the word, 'Homo sapiens'
extracted_block = block '//\n'
for line in extracted_block.strip().split('\n'): # divide each block into lines
if line.startswith('DR '):
dr = line
elif line.startswith('FT '):
ft = line
我根據'//'(塊)讀取input_file。而且,如果塊中包含“智人”這個詞,我提取了塊。此外,在塊中,以“DR”開頭的行定義為 dr,以“FT”開頭的行定義為 ft。我應該如何使用 dr 和 ft 撰寫“輸出”以獲得“預期輸出”?
uj5u.com熱心網友回復:
您可以撰寫一個帶有標志的簡單決議器。總之,當您到達包含 AA 和單詞的行時,設定標志 True 以保留以下感興趣的欄位,直到到達塊末尾,在這種情況下您重置標志。
word = 'Homo sapiens'
with open(input_file, 'r') as txtin, open(output_file, 'w') as txtout:
keep = False
for line in txtin:
if keep and line.startswith(('DR', 'FT', '//')):
txtout.write(line)
if line.startswith('//'):
keep = False # reset the flag on record end
elif line.startswith('AA') and word in line:
keep = True
輸出:
DR ac
FT ae
//
DR cc
FT ce
//
注意。這要求 AA 在要保存的欄位之前。如果沒有,您必須使用類似的邏輯逐塊決議(將資料保存在記憶體中)
uj5u.com熱心網友回復:
如果您對基于正則運算式的解決方案持開放態度,那么一種選擇是將整個檔案讀入一個字串,然后使用re.findall:
with open(input_file, 'r') as file:
inp = file.read()
matches = re.findall(r'(?<=//\n)ID.*?\nAA\s Homo sapiens\n(DR\s \w \n)BB\s \w \n(FT\s \w \n//\n?)', '//\n' inp)
for match in matches:
for line in match:
print(line, end='')
這列印:
DR ac
FT ae
//
DR cc
FT ce
//
這是一個演示,顯示該模式可以正確識別每個匹配塊內的塊和 DR/FT 線。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388182.html
上一篇:如何使用熊貓資料列印圖形?
