【问题标题】:How to relate two object in a json file when searching?搜索时如何关联json文件中的两个对象?
【发布时间】:2021-12-18 07:29:05
【问题描述】:

我正在使用 Twitter API,它返回一个 JSON 文件。 如果您滚动到底部,他们的开发人员documentation 中有一个示例,请注意该示例仅包含 1 条推文,而我正在处理数百条推文。

data 对象中有 geo,在 geo 内部有 place_id,它与 includes 对象中的另一个字段相关,更具体地说,是嵌套在 places 下的 id 字段。

当我在data 的 JSON 文件中有数百条推文,并且在另一个对象 includes 中有它们各自的地理位置数据时,我的问题就出现了。如何提取地理位置数据并将其与我选择的当前推文相关联?

目前,我有一个 for 循环来遍历所有推文并将信息附加到 CSV 文件中,然后嵌套在该 for 循环中,我有这个:

    for place in json_response['includes']['places']:
      if (geo == place['id']):
        full_name = place['full_name']
        country = place['country']
        country_code = place['country_code']
        new_geo = place['geo']
        place_name = place['name']
        place_type = place['place_type']

但是,它只返回每个 JSON 响应的 1 条推文的地理位置数据,因为我假设每条推文都有自己的 includes 对象。现在我被困住了,任何帮助都将不胜感激。

【问题讨论】:

    标签: python json twitter twitterapi-python


    【解决方案1】:

    消除对双 for 循环和 if 语句的需要 您在代码 sn-p 中有一个直接的方法,无需额外的库,即使用 place_id 作为 dict 的键对所有推文进行 dict 理解:

    tweets = {tweet['geo']['place_id']: tweet for tweet in json_response['data']}
    

    这会产生以下列表:

    {'01a9a39529b27f36': {'text': 'We’re sharing a live demo of the new Twitter Developer Labs program, led by a member of our DevRel team, @jessicagarson #TapIntoTwitter [url_intentionally_removed],
      'id': '1136048014974423040',
      'geo': {'place_id': '01a9a39529b27f36'}}}
    

    如果响应返回多条推文,正如您所提到的,您的用例是这样的: ['01a9a39529b27f36', 'some_other_id', ...]

    在下一步中,我们可以定义每个place 的 id 的字典理解,这样我们可以避免任何 if 语句:

    places = { p['id']: p for p in json_response['includes']['places']}  
    

    这会产生以下结果:

    {'01a9a39529b27f36': {'geo': {'type': 'Feature',
       'bbox': [-74.026675, 40.683935, -73.910408, 40.877483],
       'properties': {}},
      'country_code': 'US',
      'name': 'Manhattan',
      'id': '01a9a39529b27f36',
      'place_type': 'city',
      'country': 'United States',
      'full_name': 'Manhattan, NY'}}
    

    最后,根据公共密钥将它们组合起来:

    for pid, geodata in places.items(): tweets[pid].update(geodata) 
    

    产生:

    {'01a9a39529b27f36': {'text': 'We’re sharing a live demo of the new Twitter Developer Labs program, led by a member of our DevRel team, @jessicagarson #TapIntoTwitter [url_removed_on_purpose],
      'id': '01a9a39529b27f36',
      'geo': {'type': 'Feature',
       'bbox': [-74.026675, 40.683935, -73.910408, 40.877483],
       'properties': {}},
      'country_code': 'US',
      'name': 'Manhattan',
      'place_type': 'city',
      'country': 'United States',
      'full_name': 'Manhattan, NY'}}
    

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多