如何使用python计算和打印json对象中的unque单词

时间:2016-11-22 13:32:17

标签: python json dictionary

我正在尝试打印多个json对象的count和unique属性。我的数据如下:

[
      {
        "category": [
                     "Fast Food",
                      "Restaurants"
                    ]
      },
      {
          "category": [
                        "Nightlife"
                      ]
      },
      {
          "category": [
                        "Bars",
                        "American (New)",
                        "Nightlife",
                        "Lounges",
                        "Restaurants"
                      ]
      }
]

我的问题是如何计算类别中唯一单词的数量。例如餐厅总共出现2次,依此类推。我正在尝试使用python。需要帮助

1 个答案:

答案 0 :(得分:1)

您可以使用collections.Counter执行此操作:

from collections import Counter

json = #your json object
total = [dic['category'] for dic in json]
total = [cat for sublist in total for cat in sublist] # Flatten the list

Counter(total)

输出

Counter({'American (New)': 1,
         'Bars': 1,
         'Fast Food': 1,
         'Lounges': 1,
         'Nightlife': 2,
         'Restaurants': 2})