首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从以下接口响应中获取特定的配对

如何从以下接口响应中获取特定的配对
EN

Stack Overflow用户
提问于 2020-03-01 21:36:27
回答 2查看 109关注 0票数 1

我从api收到的响应格式如下:

代码语言:javascript
复制
"NetRange: 185.0.0.0 - 185.255.255.255 CIDR: 185.0.0.0/8 NetName: RIPE-185 NetHandle: NET-185-0-0-0-1 Parent: () NetType: Allocated to RIPE NCC OriginAS: Organization: RIPE Network Coordination Centre (RIPE) RegDate: 2011-01-04 Updated: 2011-02-08 Comment: These addresses have been further assigned to users in Comment: the RIPE NCC region. Contact information can be found in Comment: the RIPE database at http://www.ripe.net/whois Ref: https://rdap.arin.net/registry/ip/185.0.0.0 ResourceLink: https://apps.db.ripe.net/search/query.html ResourceLink: whois.ripe.net **OrgName: RIPE Network Coordination Centre** OrgId: RIPE Address: P.O. Box 10096 City: Amsterdam StateProv: PostalCode: 1001EB Country: NL RegDate: Updated: 2013-07-29 Ref: https://rdap.arin.net/registry/entity/RIPE ReferralServe "

但我只需要突出显示的值对。在python中,同样的内容到底应该如何格式化呢?我使用的是python 3。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-01 22:13:49

您可以使用re正则表达式模块执行此操作:

代码语言:javascript
复制
import re

#assume that resp is response from API
resp = "NetRange: 185.0.0.0 - 185.255.255.255 CIDR: 185.0.0.0/8 NetName: RIPE-185 NetHandle: NET-185-0-0-0-1 Parent: () NetType: Allocated to RIPE NCC OriginAS: Organization: RIPE Network Coordination Centre (RIPE) RegDate: 2011-01-04 Updated: 2011-02-08 Comment: These addresses have been further assigned to users in Comment: the RIPE NCC region. Contact information can be found in Comment: the RIPE database at http://www.ripe.net/whois Ref: https://rdap.arin.net/registry/ip/185.0.0.0 ResourceLink: https://apps.db.ripe.net/search/query.html ResourceLink: whois.ripe.net OrgName: RIPE Network Coordination Centre OrgId: RIPE Address: P.O. Box 10096 City: Amsterdam StateProv: PostalCode: 1001EB Country: NL RegDate: Updated: 2013-07-29 Ref: https://rdap.arin.net/registry/entity/RIPE ReferralServe "

regex = r"OrgName:\s(.+?)\sOrgId"
orgName = re.findall(regex, resp)[0]
print(orgName) #RIPE Network Coordination Centre
票数 0
EN

Stack Overflow用户

发布于 2020-03-01 22:58:27

这是您正在获取的数据的一个简单解析器:

代码语言:javascript
复制
def parse_reply(data):
    tmp = []
    result = {}
    kvdata = data.split()
    key = kvdata[0]
    for e in kvdata[1:]:
        if e.endswith(':'):
            result[key] = " ".join(tmp)
            key = e[:-1]
            tmp.clear()
        else:
            tmp.append(e)
    return result


rep = parse_reply(data)
print(rep['OrgName'])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60475655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档