Get and print a histogram of the top 15 brand distribution for a search query. Histograms are created by using the "Facets" functionality of the API. A Facet is a view of a certain property of products, containing a number of buckets, one for each value of that property. Or concrete
()
| 14 | |
| 15 | |
| 16 | def main(): |
| 17 | """Get and print a histogram of the top 15 brand distribution for a search |
| 18 | query. |
| 19 | |
| 20 | Histograms are created by using the "Facets" functionality of the API. A |
| 21 | Facet is a view of a certain property of products, containing a number of |
| 22 | buckets, one for each value of that property. Or concretely, for a parameter |
| 23 | such as "brand" of a product, the facets would include a facet for brand, |
| 24 | which would contain a number of buckets, one for each brand returned in the |
| 25 | result. |
| 26 | |
| 27 | A bucket contains either a value and a count, or a value and a range. In the |
| 28 | simple case of a value and a count for our example of the "brand" property, |
| 29 | the value would be the brand name, eg "sony" and the count would be the |
| 30 | number of results in the search. |
| 31 | """ |
| 32 | client = build("shopping", SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY) |
| 33 | resource = client.products() |
| 34 | request = resource.list( |
| 35 | source="public", |
| 36 | country="US", |
| 37 | q="digital camera", |
| 38 | facets_include="brand:15", |
| 39 | facets_enabled=True, |
| 40 | ) |
| 41 | response = request.execute() |
| 42 | |
| 43 | # Pick the first and only facet for this query |
| 44 | facet = response["facets"][0] |
| 45 | |
| 46 | print('\n\tHistogram for "%s":\n' % facet["property"]) |
| 47 | |
| 48 | labels = [] |
| 49 | values = [] |
| 50 | |
| 51 | for bucket in facet["buckets"]: |
| 52 | labels.append(bucket["value"].rjust(20)) |
| 53 | values.append(bucket["count"]) |
| 54 | |
| 55 | weighting = 50.0 / max(values) |
| 56 | |
| 57 | for label, value in zip(labels, values): |
| 58 | print(label, "#" * int(weighting * value), "(%s)" % value) |
| 59 | |
| 60 | print() |
| 61 | |
| 62 | |
| 63 | if __name__ == "__main__": |
no test coverage detected
searching dependent graphs…