如何从下面的api响应中获取特定对

2024-05-23 23:07:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我从api收到的回复格式如下:

"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


Tags: thetoinhttpsnetcommentnetworkwhois
2条回答

可以使用^{}正则表达式模块执行此操作:

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

这是一个简单的数据解析器:

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'])

相关问题 更多 >