2015-04-01 25 views
1

如果我在變量中使用了以下文本,能夠使用"NetName:"進行搜索並獲得"LVLT-GOGL-8-8-8"返回的最佳方式是什麼?如何使用Python在列中查找文本

NetRange:  8.8.8.0 - 8.8.8.255 

CIDR:   8.8.8.0/24 

NetName:  LVLT-GOGL-8-8-8 

NetHandle:  NET-8-8-8-0-1 

Parent:   LVLT-ORG-8-8 (NET-8-0-0-0-1) 

NetType:  Reallocated 

NetType:  Reallocated 

OriginAS: 

Organization: Google Inc. (GOGL) 

RegDate:  2014-03-14 

Updated:  2014-03-14 

Ref:   http://whois.arin.net/rest/net/NET-8-8-8-0-1 

回答

1

您可以使用正則表達式,在這種情況下可能做這項工作:

>>> s="""NetRange:  8.8.8.0 - 8.8.8.255 
... 
... CIDR:   8.8.8.0/24 
... 
... NetName:  LVLT-GOGL-8-8-8 
... 
... NetHandle:  NET-8-8-8-0-1 
... 
... Parent:   LVLT-ORG-8-8 (NET-8-0-0-0-1) 
... 
... NetType:  Reallocated 
... 
... NetType:  Reallocated 
... 
... OriginAS: 
... 
... Organization: Google Inc. (GOGL) 
... 
... RegDate:  2014-03-14 
... 
... Updated:  2014-03-14 
... 
... Ref:   http://whois.arin.net/rest/net/NET-8-8-8-0-1""" 
>>> import re 

>>> re.search(r'NetName:\s+(.*)',s).group(1) 
'LVLT-GOGL-8-8-8' 

或者你也可以遍歷分割後的字符串,並用生成器表達式:

>>> next(line.split()[-1] for line in s.split('\n') if 'NetName:' in line) 
'LVLT-GOGL-8-8-8' 
+0

工作很好,謝謝! – gamarga 2015-04-06 18:02:15

+0

@gamarga歡迎!那麼接受答案呢? ;) – Kasramvd 2015-04-06 18:04:09

+1

完成! (我不得不穀歌如何接受答案,新手在家裏呃?!) – gamarga 2015-04-06 18:22:30

0
#!/usr/bin/env python 
import re 

ff = """NetRange:  8.8.8.0 - 8.8.8.255 

CIDR:   8.8.8.0/24 

NetName:  LVLT-GOGL-8-8-8 

NetHandle:  NET-8-8-8-0-1 

Parent:   LVLT-ORG-8-8 (NET-8-0-0-0-1) 

NetType:  Reallocated 

NetType:  Reallocated 

OriginAS: 

Organization: Google Inc. (GOGL) 

RegDate:  2014-03-14 

Updated:  2014-03-14 

Ref:   http://whois.arin.net/rest/net/NET-8-8-8-0-1""" 


m = re.search("NetRange:(.*)\n", ff) 
print m.groups() # or do 
print m.group(1) 
相關問題