樣本資料:-。
集團資訊。
名稱 目標 狀態 角色 模式 選項
SG_hpux_vgcgloack.r518634 s2976 啟動 初級同步 auto_recover,auto_failover,path_management,auto_synchronize,active_active
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
vgcglock_SG_cluster 13496 vgcglock_SG_cluster 28505 Synced NA
名稱 目標 狀態 角色 模式 選項
aix_rcg1_AA.r518634 s2976 開始 主要同步 auto_recover,auto_failover,path_management,auto_synchronize,active_active
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
tpvvA_aix_r.2 20149 tpvvA_aix.2 41097 Synced NA
tpvvA_aix_r.3 20150 tpvvA_aix.3 41098 Synced NA
tpvvA_aix_r.4 20151 tpvvA_aix.4 41099 Synced NA
名稱 目標 狀態 角色 模式 選項
aix_rcg2_AA.r518634 s2976 開始 初級同步 auto_recover,auto_failover,path_management,auto_synchronize,active_active
LocalVV ID RemoteVV ID SyncStatus LastSyncTime
decoA_aix_r.11 20158 decoA_aix.11 41106 Synced NA
decoA_aix_r.12 20159 decoA_aix.12 41107 Synced NA
decoA_aix_r.13 20160 decoA_aix.13 41108 Synced NA
我想搜索 "姓名 "一行和緊接著的下一行,并將其作為Key。值。
代碼:-
##該檔案很大,這里沒有顯示的代碼從組資訊行提取資料。
##并保存到 "no_extra_lines."。
# 在這里,我正在洗掉空行或空字串。
no_extra_lines = [line for line in required_lines if line.strip() != " "]
print(no_extra_lines)
print(len(no_extra_lines))
#here I want to iterrate over the string and want to extract the line "Name" and the immedite next line.
for num, line in enumerate(no_extra_lines)。
print(num, line)
if "Name" in line:
print(line)
print(line 1)
如何列印該行和下一行?或者換一種方式,我怎樣才能在每次出現 "Name "后提取下一組行。 這個串列非常大,有相同的模式。我想在每次出現時提取這兩行,并保存為一個鍵值。
uj5u.com熱心網友回復:
你應該使用num提取下一行,它是當前行的索引
for num, line in enumerate(no_extra_lines):
print(num, line)
if "Name" in line:
print(line)
print(no_extract_lines[num 1] )
uj5u.com熱心網友回復:
在字串print(line 1)中,你試圖向字串添加一個數字,你需要從串列中獲取當前值之后的下一個值。你可以這樣做:
if "Name" in line:
print(line)
print(no_extra_lines[num 1]
uj5u.com熱心網友回復:
既然你說 "串列是巨大的",我建議使用一種只使用迭代并避免索引的方法:
def extract_name_next(lines)。
it = (line for line in lines if line.strip() != ' ')
for line in it:
if line.startinwith('Name')。
key = line
try:
value = next(it)
yield key, value
except StopIteration:
raise ValueError('Name must be followedd by additional line' )
這是一個生成器函式,產生(鍵,值)對。為了列印,你可以像這樣使用它
for key, value in extract_name_next(required_lines) 。
print(key)
print(value)
你也可以從這些資料對中構造一個dict:
mydict = dict(extract_name_next(required_lines) )
注意,你也可以用這個生成器從檔案等中提取鍵值對,即使該檔案不適合在RAM中使用:
with open(' huge_file') as file。
mydict = dict(extract_name_next(file) )
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/309355.html
標籤:
上一篇:為物件分配類別的問題
