【问题标题】:Parsing Web Data in Python (Using Strings)在 Python 中解析 Web 数据(使用字符串)
【发布时间】:2020-06-23 17:44:18
【问题描述】:

我有一个来自网络抓取的 Python 列表,如下所示。

['\n           Elementary School: HUTCHINSON \n           High School: RIVERSIDE \n           Middle School: ROLLING RIDGE \n  ... ] 

我的目标是检索我提取的每个列表的高中名称。对于此特定列表,高中位于 RIVERSIDE。提取此信息的最佳方法是什么?

我的目标是为这个特定列表创建一个变量 hs = "RIVERSIDE"

旁注:此数据来自 realtor.com 上的房屋清单

【问题讨论】:

    标签: python python-3.x parsing text


    【解决方案1】:

    你可以试试这个:

    ls=['\n           Elementary School: HUTCHINSON \n           High School: RIVERSIDE \n           Middle School: ROLLING RIDGE \n ']
    
    
    hs=[i.strip().split(':')[1].replace('\n','') for i in ls[0].split('\n') if 'High School' in i][0]
    print('hs =',hs)
    

    输出:

    hs =  RIVERSIDE
    

    或者你可以使用re:

    import re 
    highschoolregex = re.compile(r'(High School)[:] (\w.+)') 
    hs = highschoolregex.search(ls[0]).group(2)
    print('hs =',hs)
    

    输出:

    hs =  RIVERSIDE
    

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 2011-06-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多