如何在带有 Python 的列中查找文本

How to find text in a column with Python

如果我在变量中包含以下文本,那么能够使用 say "NetName:" 进行搜索并返回 "LVLT-GOGL-8-8-8" 的最佳方法是什么?

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

您可以使用正则表达式,在这种情况下 re.search 可以完成工作:

>>> 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'
#!/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)