使用正則表示式和json.loads,將JSON檔案中的資料轉化為pandas.DataFrame
阿新 • • 發佈:2018-12-02
使用正則表示式和json.loads,將JSON檔案中的資料轉化為pandas.DataFrame
說在前面
在使用Scrapy框架(爬蟲框架)爬取網頁資訊時,會定義一個ITEMS,然後通過PIPLINE將資料寫入到JSON檔案中,如果是按行寫入,則最後得到的資料就不是一個標準JSON格式的資料,在進行資料分析時,就會比較艱難。所以本文旨在用兩種方法解決這個問題。
方法說明
本文分別使用Python中的re[正則表示式]模組和json模組來擴充套件的兩種方式。
- 正則表示式方法:
原理
首先,先將JSON檔案中的內容讀出來,然後用正則表示式將文字中為null的資料進行替換。然後取出相應標籤的對應的值,再將對應的值封裝為Series,最後在構造成一個DataFrame資料。
詳細程式碼
#coding='utf-8 import pandas as pd import re class DataAnalysis(object): def __init__(self): # self.data_str = open("boss_fp.json",encoding='utf-8').read() # self.data_str = open("boos_dat.json",encoding='utf-8').read() self.data_str = None self.data_f = None def data_ana(self,json_str): p = re.compile(r'"title":"(.*?),"') title = p.findall(json_str) # print(title) p2 = re.compile(r'"salary":"(.*?)"') salary = p2.findall(json_str) # print(salary) p2 = re.compile(r'company_name":"(.*?),"') company_name = p2.findall(json_str) # print(company_name) p2 = re.compile(r'"company_info":\[(.*?)\]') company_info = p2.findall(json_str) # print(company_info) p2 = re.compile(r'"work_time":"(.*?)"') work_time = p2.findall(json_str) # print(work_time) p2 = re.compile(r'"education":"(.*?)"') education = p2.findall(json_str) # print(education) p2 = re.compile(r'"datail_count"(:.*?)}') datail_count = p2.findall(json_str) # print(datail_count) print(len(title),len(salary),len(company_name),len(company_info),len(work_time),len(education),len(datail_count)) title_s = pd.Series(title) salary_s = pd.Series(salary) company_name_s = pd.Series(company_name) company_info_s = pd.Series(company_info) work_time_s = pd.Series(work_time) education_s = pd.Series(education) datail_count_s = pd.Series(datail_count) self.data_f = pd.DataFrame([title_s,salary_s,company_name_s,company_info_s,work_time_s,education_s,datail_count_s],index=['title','salary','company_name','company_info','work_time','education','datail_count']) data_fz = self.data_f.T print(data_fz.info()) def data_sort_out(self): self.data_str = open("boss_fp.json", encoding='utf-8').read() data_re = re.sub(r"}","}#",self.data_str) re_data1 = re.sub(r'null','"is_null"',data_re) re_data = re.sub(r"\s|\\n|\r|\\t","",re_data1) with open("boos_dat.json",'w',encoding='utf-8') as fp: fp.write(re_data) return re_data if __name__ == '__main__': dataf = DataAnalysis() json_str = dataf.data_sort_out() dataf.data_ana(json_str)
執行結果
3. json包方法:
利用json包的方法是分為如下幾個步驟:
1.將不規則的json資料修改為規則的json資料
2.在使用json.loads()將資料轉化為python物件
3.構造成DateFrame
fp = open("boss_fp.json",'r',encoding='utf-8').read() #將字串中的"}"修改為"}." fp_re = re.sub(r"}","},",fp) #去掉最後一個“,”,在字串的首尾新增"[]" fp_re = "["+fp_re[:-2]+"]" #轉化為python物件 json_str = json.loads(fp_re) print(type(json_str)) #構造DataFrame df = pd.DataFrame(json_str) print(df.info())
執行結果