如何使用Wikidata API访问语句

我正试图从Wikidata获取信息。例如,要使用“ cobalt-70”,请使用API​​。

BufferedPaintRenderAnimation()

因此有一个“声明”可以访问这些语句。有没有最好的方法来检查语句中是否存在值?例如,“钴70”在属性P2114内部的值为0.5。那么,如何检查实体的语句中是否存在值?作为此示例。

如何使用Wikidata API访问语句

是否有访问它的方法。谢谢!

iCMS 回答:如何使用Wikidata API访问语句

我不确定这正是您要寻找的东西,但是如果距离足够近,您可以根据需要进行修改:

import requests
import json
url = 'https://www.wikidata.org/wiki/Special:EntityData/Q18844865.json'
req = requests.get(url)
targets = j_dat['entities']['Q18844865']['claims']['P2114']
for target in targets:    
    values = target['mainsnak']['datavalue']['value'].items()
    for value in values:
        print(value[0],value[1])

输出:

amount +0.5
unit http://www.wikidata.org/entity/Q11574
upperBound +0.6799999999999999
lowerBound +0.32
amount +108.0
unit http://www.wikidata.org/entity/Q723733
upperBound +115.0
lowerBound +101.0

编辑: 要按值查找属性ID,请尝试:

targets = j_dat['entities']['Q18844865']['claims'].items()
for target in targets:   
    line = target[1][0]['mainsnak']['datavalue']['value']
    if isinstance(line,dict):
        for v in line.values():
            if v == "+0.5":
                print('property: ',target[0])

输出:

property:  P2114
,

我尝试了一种解决方案,其中包括在json对象内部进行搜索,作为此处提出的解决方案:https://stackoverflow.com/a/55549654/8374738。希望对您有所帮助。让我们给你个主意。

import pprint

def search(d,search_pattern,prev_datapoint_path=''):
    output = []
    current_datapoint = d
    current_datapoint_path = prev_datapoint_path
    if type(current_datapoint) is dict:
        for dkey in current_datapoint:
            if search_pattern in str(dkey):
                c = current_datapoint_path
                c+="['"+dkey+"']"
                output.append(c)
            c = current_datapoint_path
            c+="['"+dkey+"']"
            for i in search(current_datapoint[dkey],c):
                output.append(i)
    elif type(current_datapoint) is list:
        for i in range(0,len(current_datapoint)):
            if search_pattern in str(i):
                c = current_datapoint_path
                c += "[" + str(i) + "]"
                output.append(i)
            c = current_datapoint_path
            c+="["+ str(i) +"]"
            for i in search(current_datapoint[i],c):
                output.append(i)
    elif search_pattern in str(current_datapoint):
        c = current_datapoint_path
        output.append(c)
    output = filter(None,output)
    return list(output)

您只需要使用:

pprint.pprint(search(res.json(),'0.5','res.json()'))

Output:

["res.json()['claims']['P2114'][0]['mainsnak']['datavalue']['value']['amount']"]
本文链接:https://www.f2er.com/2104095.html

大家都在问