Python — Преобразование JSON в структуру таблицы

#python #json #pandas

#python #json #pandas

Вопрос:

Я написал скрипт на python для загрузки синонимов из API и размещения его в df.

 import requests
import pandas as pd   
import json

Result = []
Begriffe = ['See','Meer','Katze']

for Begriff in Begriffe:

    # Make a get request to get the latest position of the international space station from the opennotify api.
    response = requests.get('https://www.openthesaurus.de/synonyme/search?q=' str(Begriff) 'amp;format=application/json')
    # Print the status code of the response.
    print(response.status_code)
    #200 — everything went okay, and the result has been returned (if any)
    #301 — the server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint name is changed.
    #401 — the server thinks you’re not authenticated. This happens when you don’t send the right credentials to access an API (we’ll talk about authentication in a later post).
    #400 — the server thinks you made a bad request. This can happen when you don’t send along the right data, among other things.
    #403 — the resource you’re trying to access is forbidden — you don’t have the right permissions to see it.
    #404 — the resource you tried to access wasn’t found on the server.

    data = response.json()
    df = pd.DataFrame(data['synsets'])
    Result.append({Begriff: df}) 

#df = pd.DataFrame(responses['synsets'])
print(Result)

#Metainfos
#from pandas.io.json import json_normalize
#json_normalize(data)

#create csv
df.to_csv('file_name', sep='t')
  

Результат следующий:

 [{'See':   categories    id                                              terms
0         []  2783  [{'term': 'Binnensee'}, {'term': 'Landsee'}, {...
1         []  5913  [{'term': 'See'}, {'term': 'Teich'}, {'term': ...
2         []  6605  [{'term': 'Meer'}, {'term': 'Ozean'}, {'term':...}, {'Meer':   categories    id                                              terms
0         []  6605  [{'term': 'Meer'}, {'term': 'Ozean'}, {'term':...}, {'Katze':    categories     id                                              terms
0          []  11537  [{'term': 'Hauskatze'}, {'term': 'Katze'}, {'t...
1  [Zoologie]  14012  [{'term': 'Katze'}, {'term': 'Felidae (Familie...}]
  

Что мне сейчас нужно, так это взять только термины столбца

 [{'term': 'Meer'}, {'term': 'Ozean'}, {'term': '(die) See'}, {'term': 'Weltmeer', 'level': 'gehoben'}]
  

и поместить его в структуру, подобную этой:

 term   |  terms 
Meer   |  Ozean
Meer   |  See
Meer   |  Weltmeer
  

Редактировать
С помощью следующего скрипта:

 def dict_get(x,key,here=None):
    x = x.copy()
    if here is None: here = []
    if x.get(key):  
        here.append(x.get(key))
        x.pop(key)
    else:
        for i,j in x.items():
          if  isinstance(x[i],list): dict_get(x[i][0],key,here)
          if  isinstance(x[i],dict): dict_get(x[i],key,here)
    return here 
     
  

Итак, по крайней мере, я получаю следующий результат:

 [[{'term': 'Boden'},
  {'term': 'Grund'},
  {'term': 'Grund und Boden'},
  {'term': 'Land'}]]
  

Но что мне действительно было бы нужно, так это структура таблицы

Комментарии:

1. определить dict_get(x,ключ, здесь= Нет): x = x.copy() если здесь нет: здесь = [] если x.get(ключ): здесь.append(x.get(ключ)) x.pop(ключ) else: для i, j в x.items(): если isinstance(x[i],список): dict_get(x[i][0], ключ, здесь) если isinstance(x[i],dict): dict_get(x[i], ключ, здесь) возвращает здесь

Ответ №1:

 df[["term", "terms"]].to_csv('file_name', sep='t')