【问题标题】:How to find text in a column with Python如何使用 Python 在列中查找文本
【发布时间】:2015-04-01 19:09:41
【问题描述】:

如果我在变量中包含以下文本,那么使用 "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

【问题讨论】:

    标签: python parsing text split find


    【解决方案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'
    

    【讨论】:

    • @gamarga 欢迎您!那么接受答案呢? ;)
    • 完成! (我不得不谷歌如何接受答案,新手在家里嗯?!)
    【解决方案2】:
    #!/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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      相关资源
      最近更新 更多