Python【8】-分析json文件


一、本節用到的基礎知識

1.逐行讀取文件

for line in open('E:\Demo\python\json.txt'):
    print line

 

2.解析json字符串

Python中有一些內置模塊可以非常便捷地將json字符串轉換為Python對象。比如json模塊中的json.relaods()方法可以將json字符串解析為相應的字典。

import json

s='{ "a": "GoogleMaps\/RochesterNY", "c": "US", "nk": 0, "tz": "America\/Denver", "gr": "UT", "g": "mwszkS", "h": "mwszkS", "l": "bitly", "hh": "1.usa.gov", "r": "http:\/\/www.AwareMap.com\/", "u": "http:\/\/www.monroecounty.gov\/etc\/911\/rss.php", "t": 1331926741, "hc": 1308262393, "cy": "Provo", "ll": [ 40.218102, -111.613297 ] }'
o=json.loads(s)
print o

 

運行結果:

{u'a': u'GoogleMaps/RochesterNY', u'c': u'US', u'nk': 0, u'tz': u'America/Denver', u'gr': u'UT', u'g': u'mwszkS', u'h': u'mwszkS', u'cy': u'Provo', u'l': u'bitly', u'hh': u'1.usa.gov', u'r': u'http://www.AwareMap.com/', u'u': u'http://www.monroecounty.gov/etc/911/rss.php', u't': 1331926741, u'hc': 1308262393, u'll': [40.218102, -111.613297]}

 

3.列表生成式

詳見:http://www.cnblogs.com/janes/p/5530979.html

二、將json文件解析為字典列表

要對json文件進行分析,首先我們逐行讀取該文件,並把每行轉換成對應的字典對象,然后組成一個列表。

import json
#讀取文件並解析為字典組成的列表
dicList=[json.loads(line) for line in open('E:\Demo\python\json.txt')]
#打印第一個字典元素
print dicList[0]
#打印第一個元素中的時區
print dicList[0]['tz']

 

運行結果:

{u'a': u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.78 Safari/535.11', u'c': u'US', u'nk': 1, u'tz': u'America/New_York', u'gr': u'MA', u'g': u'A6qOVH', u'h': u'wfLQtf', u'cy': u'Danvers', u'l': u'orofrog', u'al': u'en-US,en;q=0.8', u'hh': u'1.usa.gov', u'r': u'http://www.facebook.com/l/7AQEFzjSi/1.usa.gov/wfLQtf', u'u': u'http://www.ncbi.nlm.nih.gov/pubmed/22415991', u't': 1331923247, u'hc': 1331822918, u'll': [42.576698, -70.954903]}

America/New_York

三、利用Python標准庫統計json文件中的時區數據

1.首先將所有時區數據放在一個列表中

#獲取所有時區數據
timezones=[item['tz'] for item in dicList if 'tz' in item]
#測試打印前五條
print timezones[0:5]

 

運行結果:

[u'America/New_York', u'America/Denver', u'America/New_York', u'America/Sao_Paulo', u'America/New_York']

2.然后將時區列表轉換為時區計數字典,key為時區名,value為出現次數。

#自定義函數,統計時區出現次數
def countZone(timezones):
    count_zone={}
    for tz in timezones:
        if(tz in count_zone):
            count_zone[tz]+=1
        else:
            count_zone[tz]=1
    return count_zone

#自定義函數,返回top N
def countTop(dicCount,n):
    valueKeyItems=[(value,key) for key,value in dicCount.items()]
    valueKeyItems.sort()
    return valueKeyItems[-n:]
    
#測試並打印出現次數最多的5個時區    
count=countZone(timezones)
print countTop(count,5)

 

運行結果:

[(191, u'America/Denver'), (382, u'America/Los_Angeles'), (400, u'America/Chicago'), (521, u''), (1251, u'America/New_York')]

3.利用defaultdict簡化函數countZone函數

Python標准庫collections對一些數據結構進行了拓展操作,使用起來更加便捷,其中defaultdict可以給字典賦值默認value。

from collections import defaultdict,Counter
def countZone(timezones):
    count_zone=defaultdict(int)
    for tz in timezones:
        count_zone[tz]+=1
    return count_zone

 

4.利用collections.Counter簡化countTop函數

from collections import Counter

def countTop(dicCount,n):
    return Counter(dicCount).most_common(n)

 

5.完整代碼

# -*- coding: utf-8 -*-
import json
#1.讀取文件並轉換為字典列表
#讀取文件並解析為字典組成的列表
dicList=[json.loads(line) for line in open('E:\Demo\python\json.txt')]

#2.統計時區
#獲取所有時區數據
timezones=[item['tz'] for item in dicList if 'tz' in item]

#統計時區出現次數
from collections import defaultdict,Counter
def countZone(timezones):
    count_zone=defaultdict(int)
    for tz in timezones:
        count_zone[tz]+=1
    return count_zone

#返回top N
def countTop(dicCount,n):
    return Counter(dicCount).most_common(n)
    
#測試並打印出現次數最多的5個時區    
count=countZone(timezones)
print countTop(count,5)

 

#運行結果:[(u'America/New_York', 1251), (u'', 521), (u'America/Chicago', 400), (u'America/Los_Angeles', 382), (u'America/Denver', 191)]

四 利用pandas統計json文件中的時區數據

1.運用DataFrame統計時區數據

①DataFrame是pandas中很常用的數據結構,它把數據轉換為一個類似表格的結構。

# -*- coding: utf-8 -*-
import json
from pandas import DataFrame
dicList=[json.loads(line) for line in open('E:\Demo\python\json.txt')]
frame=DataFrame(dicList)
#測試打印時區列表中前5個元素
print frame['tz'][:5]

 

運行結果:

0     America/New_York

1       America/Denver

2     America/New_York

3    America/Sao_Paulo

4     America/New_York

②frame['tz']有value_counts()函數,可以直接返回對應的計數。

#打印出現次數最多的5個時區

print frame['tz'].value_counts()[:5]

 

運行結果:

America/New_York       1251

                                 521

America/Chicago         400

America/Los_Angeles     382

America/Denver          191

③為不存在時區數據或者時區為空字符串的數據補全默認值。

fillna()函數可以補全不存在的字段;空字符串可以通過布爾型索引的形式進行替換。

tzList=frame['tz'].fillna('Missing')
tzList[tzList =='']='Unknown'
print tzList.value_counts()[:5]

 

運行結果:

America/New_York       1251

Unknown                 521

America/Chicago         400

America/Los_Angeles     382

America/Denver          191

這樣我們就完成了之前用標准Python庫相同的工作,完整代碼如下:

# -*- coding: utf-8 -*-
import json
from pandas import DataFrame
dicList=[json.loads(line) for line in open('E:\Demo\python\json.txt')]
frame=DataFrame(dicList)
#打印出現次數最多的5個時區
print frame['tz'].value_counts()[:5]

#補全時區不存在或者為空的情況
tzList=frame['tz'].fillna('Missing')
tzList[tzList =='']='Unknown'
print tzList.value_counts()[:5]

 

2.利用plot方法繪制垂直條形圖

參考:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html

tzList.value_counts()[:5].plot(kind='bar',rot=0)

運行:我們可以利用%paste命令將代碼粘貼運行。

命令行:

ipython

%pylab

%paste

 

運行結果:

Image

本文用到的json文件:點此下載

參考:《利用Python進行數據分析》

如需轉載,請標明出處:http://www.cnblogs.com/janes/p/5546673.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM