正确读取 JSON 个文件
Read JSON file correctly
我正在尝试读取 Python 中的 JSON 文件(BioRelEx 数据集:https://github.com/YerevaNN/BioRelEx/releases/tag/1.0alpha7)。 JSON 文件是一个对象列表,每个句子一个。
这就是我尝试这样做的方式:
def _read(self, file_path):
with open(cached_path(file_path), "r") as data_file:
for line in data_file.readlines():
if not line:
continue
items = json.loads(lines)
text = items["text"]
label = items.get("label")
我的代码在 items = json.loads(line)
上失败了。看起来数据没有按照代码预期的那样格式化,但我该如何更改呢?
提前感谢您的宝贵时间!
最佳,
茱莉亚
您的代码一次读取一行并将每一行单独解析为 JSON。除非文件的创建者以这种格式创建文件(假设它有一个 .json 扩展名是不可能的)那么这将不起作用,因为 JSON 不使用换行符来指示结束一个东西。
将整个文件内容加载为 JSON,然后处理数组中的结果项。
def _read(self, file_path):
with open(cached_path(file_path), "r") as data_file:
data = json.load(data_file)
for item in data:
text = item["text"]
标签似乎埋在项目["interaction"]
中
使用 json.load()
你不需要阅读每一行,你可以执行以下任一操作:
import json
def open_json(path):
with open(path, 'r') as file:
return json.load(file)
data = open_json('./1.0alpha7.dev.json')
或者,更酷的是,您可以从 GitHub
获取 json
import json
import requests
url = 'https://github.com/YerevaNN/BioRelEx/releases/download/1.0alpha7/1.0alpha7.dev.json'
response = requests.get(url)
data = response.json()
这些都将给出相同的输出。 data
变量将是一个字典列表,您可以在 for
循环中对其进行迭代并进行进一步处理。
我正在尝试读取 Python 中的 JSON 文件(BioRelEx 数据集:https://github.com/YerevaNN/BioRelEx/releases/tag/1.0alpha7)。 JSON 文件是一个对象列表,每个句子一个。 这就是我尝试这样做的方式:
def _read(self, file_path):
with open(cached_path(file_path), "r") as data_file:
for line in data_file.readlines():
if not line:
continue
items = json.loads(lines)
text = items["text"]
label = items.get("label")
我的代码在 items = json.loads(line)
上失败了。看起来数据没有按照代码预期的那样格式化,但我该如何更改呢?
提前感谢您的宝贵时间!
最佳,
茱莉亚
您的代码一次读取一行并将每一行单独解析为 JSON。除非文件的创建者以这种格式创建文件(假设它有一个 .json 扩展名是不可能的)那么这将不起作用,因为 JSON 不使用换行符来指示结束一个东西。
将整个文件内容加载为 JSON,然后处理数组中的结果项。
def _read(self, file_path):
with open(cached_path(file_path), "r") as data_file:
data = json.load(data_file)
for item in data:
text = item["text"]
标签似乎埋在项目["interaction"]
中使用 json.load()
你不需要阅读每一行,你可以执行以下任一操作:
import json
def open_json(path):
with open(path, 'r') as file:
return json.load(file)
data = open_json('./1.0alpha7.dev.json')
或者,更酷的是,您可以从 GitHub
获取 jsonimport json
import requests
url = 'https://github.com/YerevaNN/BioRelEx/releases/download/1.0alpha7/1.0alpha7.dev.json'
response = requests.get(url)
data = response.json()
这些都将给出相同的输出。 data
变量将是一个字典列表,您可以在 for
循环中对其进行迭代并进行进一步处理。