wikidata文件提取

问题:我需要把下面wikidata的某些数据提取出来,最后提取结果保存为json,xlsx等文件。

1.文件太大,就不上传了,文件内容来自wikidata。
2.具体来说,提取某个人的father,mother,sibling,spouse,child,relative,sex or gender, country of citizenship这些。

img

  1. 可以参考这段代码,大的json文件解析
import ijson

user_to_repos = {}

with open("large-file.json", "rb") as f:
    for record in ijson.items(f, "item"):
        user = record["actor"]["login"]
        repo = record["repo"]["name"]
        if user not in user_to_repos:
            user_to_repos[user] = set()
        user_to_repos[user].add(repo)
  1. 大的json文件写入
with open('big_json_array.json', 'w') as out:
    json.dump(data, out)

import json

with open('你的wikidata文件路径', 'r') as f:  # 读取
    data = json.loads(f.read())
    # 这里写你的解析json的逻辑

with open('结果数据.json', 'w') as f:  # 写入
    f.write(json.dumps(data))

有一个策略,允许在不打开文件的情况下使用json模块访问信息:

import bz2
import json

with bz2.open(filename, "rt") as bzinput:
lines = []
for i, line in enumerate(bzinput):
    if i == 10: break
    tweets = json.loads(line)
    lines.append(tweets)

也可以直接跳到某一行去读取

f = bz2.BZ2File("latest-all.json.bz2", "r")
next(f)  # skip the first line
for line in f:
    json_set = json.loads(line[:-2])
    #etc...


可以考虑使用 python 的 bz2file 模块提取数据,使用 json 模块存储为json,或者使用 pandas 模块存储为excel。