你可以組使用租賃作爲分隔符與GROUPBY的部分:
from itertools import groupby
def find_ip(s, f):
with open(f) as f:
grouped = groupby(f, key=lambda x: x.startswith("lease "))
for k, v in grouped:
if k: # v is the lease line
# get ip from lease line
ip = next(v).rstrip().split()[1]
# call next to get next element from our groupby object
# which is each section after lease
val = list(next(grouped)[1])[-2]
# check for substring
if val.find(s) != -1:
return ip.rstrip("{")
return "No match"
使用輸入文件:
In [5]: find_ip('"SYSTEM123456789"',"in.txt")
Out[5]: '10.0.0.2'
x.startswith("lease ")
爲重點,以GROUPBY將文件分割成段,if k
是真的,我們與lease
一致,所以我們提取ip然後檢查租賃部分的第二行,如果我們發現子串然後返回IP。
的文件被分成行的部分看起來像如下:
[' starts 1 2015/06/29 07:22:01;\r\n', ' ends 2 2015/06/30 07:22:01;\r\n', ' tstp 2 2015/06/30 07:22:01;\r\n', ' cltt 1 2015/06/29 07:22:01;\r\n', ' binding state active; \r\n', ' next binding state free;\r\n', ' hardware ethernet 08:2e:5f:f0:8b:a1;\r\n', '}\r\n']
[' starts 1 2015/06/29 07:31:20;\r\n', ' ends 2 2015/06/30 07:31:20;\r\n', ' tstp 2 2015/06/30 07:31:20;\r\n', ' cltt 1 2015/06/29 07:31:20;\r\n', ' binding state active; \r\n', ' next binding state free;\r\n', ' hardware ethernet ec:b1:d7:87:6f:7a;\r\n', ' uid "\\001\\354\\261\\327\\207oz";\r\n', ' client-hostname "SYSTEM123456789";\r\n', '}']
你可以看到第二個最後一個元素是client-hostname
所以我們每次提取時間和搜索字符串。
如果字符串可以出現在任何地方,你可以使用任何與檢查各行:
def find_ip(s, f):
with open(f) as f:
grouped = groupby(f, key=lambda x: x.startswith("lease "))
for k, v in grouped:
if k: # v is the lease line
# get ip from lease line
ip = next(v).rstrip().split()[1]
# call next to get next element from our groupby object
# which is each section after lease
val = next(grouped)[1]
# check for substring
if any(sub.find(s) != -1 for sub in val):
return ip.rstrip("{")
return "No match"
您可以應用同樣的邏輯只是遍歷文件對象與外的內環,當你發現一個行以「lease」開頭的內容開始內部循環,直到找到子字符串並返回ip或打開}
表示該部分結束時打破內部循環。
def find_ip(s, f):
with open(f) as f:
for line in f:
if line.startswith("lease "):
ip = line.rstrip().split()[1]
for n_line in f:
if n_line.find(s) != -1:
return ip.rstrip("{")
if n_line.startswith("}"):
break
return "No match"
輸出:
In [9]: find_ip('"SYSTEM123456789"',"in.txt")
Out[9]: '10.0.0.2'
既不方法涉及在任一個時刻在存儲器中存儲的行多於一個的部分。
是'租賃..}'存儲在不同行的塊將打印IP?同時告訴我們你的嘗試。 – ssundarraj
還沒有嘗試,因爲我不知道從哪裏開始。我會打破每個塊並將其存儲在一個列表中。接下來我會用';'來分解它。 '分隔符。搜索SYSTEM123456789並搜索列表[0]以使用startswith(「租約」)查找IP。 – dreamzboy
看起來很好。你爲什麼不嘗試爲它編寫代碼? – ssundarraj