【问题标题】:How to Filter json data with python如何使用python过滤json数据
【发布时间】:2020-12-15 22:19:27
【问题描述】:

我正在尝试创建一个函数来过滤从 Google Places api 中提取的 json 数据。如果名称包含字符串“Body Shop”并且类型为 ['car_repair', 'point_of_interest', 'establishment'],我希望它返回企业名称和类型值,否则我希望它拒绝结果。到目前为止,这是我的代码。我已经尝试过,似乎无法找到一种方法来存储某些条件以使搜索更容易。

import googlemaps
import pprint
import time
import urllib.request  






API_KEY = 'YOUR_API_KEY'
lat, lng = 40.35003, -111.95206

#define our Client
gmaps = googlemaps.Client(key = API_KEY)
#Define our Search
places_result = gmaps.places_nearby(location= "40.35003,-111.95206", radius= 40000,open_now= False,type= ['car_repair','point_of_interest','establishment'])
#pprint.pprint(places_result['results'])
time.sleep(3)
places_result_2 = gmaps.places_nearby(page_token = 
places_result['next_page_token'])
pprint.pprint(places_result_2['results'])

places_result_2 = gmaps.places_nearby(page_token = 
places_result['next_page_token'])
    
types = place_details['result']['types']
name = place_details['result']['name']
def match(types,name):
  for val in types: 
      'car_repair','point_of_interest','establishment' in val and "Body Shop" in name
print(name,types)

【问题讨论】:

    标签: python json dictionary filter


    【解决方案1】:

    试试这个:

    import googlemaps
    import pprint
    import time
    import urllib.request  
    
    
    
    
    API_KEY = 'YOUR_API_KEY'
    lat, lng = 40.35003, -111.95206
    
    #define our Client
    gmaps = googlemaps.Client(key = API_KEY)
    #Define our Search
    
    places_result = gmaps.places_nearby(location= "40.35003,-111.95206", radius= 40000,open_now= False,type= ['car_repair','point_of_interest','establishment'])
    
    
    #heres how to retrieve the name of the first result
    example_of_name = places_result['results'][0]['name']
    print(example_of_name)
    
    #gets places name and type for all the results
    for place in places_result['results']:
      print("Name of Place:")
      print(place['name'])
      print("Type of the place:")
      print(place['types'], "\n")
    

    【讨论】:

    • 非常感谢!我试试看。
    • 没问题!我自己无法复制这个问题,gmaps 说places_nearby 模块不存在。如果您仍有问题,我可能会提供更多信息。
    • 谢谢!我编辑了代码以添加从 API 中实际提取的 json 结果。我认为我真正想要完成的是将多个标准存储在 python 的单个变量中,以便我可以拒绝任何不符合标准的数据。我认为 Javascript 中的等价物是创建一个 const 数组,或者至少这是一个不知道 python 的朋友所说的。
    • 问题是过滤器的标准之一需要是“名称”,每个企业名称显然会有所不同,所以我不知道如何存储它(这就是为什么你如果结果中包含字符串“Body Shop”,我会尝试过滤结果。但这显然不起作用。
    • 你好!我看到了你的问题。这是因为谷歌在您导入时将 json 信息放入列表中。它非常微妙,但它可以让您更轻松地进行迭代。我已经更新了我的代码,这样应该可以解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多