python - 如何拆分json数据集并保存?

标签 python json split pytorch

我获取了一个 json 数据集。数据集名称为 v2_OpenEnded_mscoco_train2014_questions.json 如何从数据集中拆分部分数据并将拆分数据保存到另一个 json 文件中?

这是我的数据集的示例:

{"image_id": 426004, "question": "How many buns are on the plate?", "question_id": 426004002}, {"image_id": 92846, "question": "What is the color of the vase without flowers?", "question_id": 92846000}, {"image_id": 92846, "question": "Is there anything red in this photo?", "question_id": 92846002}, {"image_id": 92846, "question": "What does that vase represent?", "question_id": 92846003}, {"image_id": 262166, "question": "What color is the couch?", "question_id": 262166002}, {"image_id": 262166, "question": "How many seats are available?", "question_id": 262166003}

我的数据集中大约有 443,757 条数据。我想将数据集拆分为 400 个不同的数据集,每个数据集都有 100 个数据。我如何使用 python 来自动化此操作? 如果可以用 pytorch 来完成这将是一个很大的帮助。

最佳答案

试试这个:

n_rows = 100
current_data = []
for i, e in enumerate(data):
    if i % n_rows == 0 and i > 0:
        with open(f'dataset_{i - n_rows}-{i}.json', 'w') as f:
            json.dump(current_data, f)
        current_data = []
    
    current_data.append(e)

data 是一个包含您拥有的 json 的列表。我们对其进行迭代,并将每 n_rows 行写入一个新文件中。最后几行没有写。

关于python - 如何拆分json数据集并保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66407955/

相关文章:

python - 如何在 Python 中将 typing.Union 转换为其子类型之一?

python - toctree嵌套下拉

python - 在经过身份验证的 session 中使用 twill/mechanize 检索 application/json 文档

python - 修复非常大的 json 文件的格式

javascript - 如何使用 JavaScript 从单独的选择列表中检索 append 值

php - chunk_split() 破坏多字节字符

python - 如何动态地制作特定数量的功能?

javascript - 如何使用字符串 : 中的函数创建对象

r - 按 R 中的分隔符行拆分数据框

python - Emacs Python "elpy"向解释器发送代码