У меня есть файл jsonl, который содержит в каждой строке как предложение, так и токены, найденные в этом предложении. Я хочу извлечь токены из каждой строки в файле строк JSON, но мой цикл возвращает токены только из последней строки.
Это вход.
{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is the second sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"second","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
Я попытался запустить следующий код:
with jsonlines.open('path/to/file') as reader:
for obj in reader:
data = obj['tokens'] # just extract the tokens
data = [(i['text'], i['id']) for i in data] # elements from the tokens
data
Фактический результат:
[('This', 0),
(«есть», 1),
('the', 2),
(«первый», 3),
(«предложение», 4),
('.', 5)]
Каков результат, к которому я хочу добраться:
![enter image description here](https://i.stack.imgur.com/xdmgG.png)
Дополнительный вопрос
Некоторые токены содержат «метку» вместо «id». Как я могу включить это в код? Примером может быть:
{"text":"This is the first sentence.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"the","id":2},
{"text":"first","id":3},
{"text":"sentence","id":4},
{"text":".","id":5}]}
{"text":"This is coded in python.","_input_hash":2083129218,"_task_hash":-536378640,"spans":[],"meta":{"score":0.5,"pattern":65},"answer":"accept","tokens":[
{"text":"This","id":0},
{"text":"is","id":1},
{"text":"coded","id":2},
{"text":"in","id":3},
{"text":"python","label":"Programming"},
{"text":".","id":5}]}