99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法
利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法
2018-05-30
收藏

利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法

下面小編就為大家分享一篇利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
假設(shè).json文件中存儲的數(shù)據(jù)為:    
{"type": "Point", "link": "http://www.dianping.com/newhotel/22416995", "coordinates": [116.37256372996957, 40.39798447055443], "category": "經(jīng)濟(jì)型", "name": "北京荷塘山莊", "count": "278", "address": "北京市懷柔區(qū)黃花城村安四路", "price": "380"}
{"type": "Point", "link": "http://www.dianping.com/newhotel/19717653", "coordinates": [116.56881588256466, 40.43310967948417], "category": "經(jīng)濟(jì)型", "name": "慕田峪長城魚師傅鄉(xiāng)村酒店", "count": "89", "address": "北京市懷柔區(qū)渤海鎮(zhèn)葦?shù)甏?慕田峪長城下3公里處,近懷黃路)", "price": "258"}
{"type": "Point", "link": "http://www.dianping.com/newhotel/58365289", "coordinates": [116.62874974822378, 40.45610264855833], "category": "經(jīng)濟(jì)型", "name": "北京蜜桃兒親子客棧", "count": "119", "address": "北京市懷柔區(qū)神堂峪風(fēng)景區(qū)下官地11號", "price": "549"}

現(xiàn)在需要將上面的這些數(shù)據(jù)存為csv格式,其中字典的keys為csv中的屬性名稱,字典的values為csv中屬性對應(yīng)的值。

如果只需要按照json的keys來生成csv,那么操作比較簡單,直接按照下面的方法即可:    
#-*-coding:utf-8-*-
import csv
import json
import sys
import codecs
def trans(path):
 jsonData = codecs.open(path+'.json', 'r', 'utf-8')
 # csvfile = open(path+'.csv', 'w') # 此處這樣寫會導(dǎo)致寫出來的文件會有空行
 # csvfile = open(path+'.csv', 'wb') # python2下
 csvfile = open(path+'.csv', 'w', newline='') # python3下
 writer = csv.writer(csvfile, delimiter='\t')
 flag = True
 for line in jsonData:
  dic = json.loads(line[0:-1])
  if flag:
   # 獲取屬性列表
   keys = list(dic.keys())
   print (keys)
   writer.writerow(keys) # 將屬性列表寫入csv中
   flag = False
  else:
   # 讀取json數(shù)據(jù)的每一行,將values數(shù)據(jù)一次一行的寫入csv中
   writer.writerow(list(dic.values()))
 jsonData.close()
 csvfile.close()
if __name__ == '__main__':
 path=str(sys.argv[1]) # 獲取path參數(shù)
 print (path)
 trans(path)

python3下運(yùn)行,命令行輸入    
python C:\Users\MaMQ\Documents\jsonToCsv.py C:\Users\MaMQ\Documents\data\geoFood

其中第三個(gè)參數(shù)為需要轉(zhuǎn)換的文件的路徑和其名稱,將其后綴刪除。運(yùn)行文件后即可得到轉(zhuǎn)換后的csv文件。

如果需要對json文件中每個(gè)字典的key字段進(jìn)行修改,比如需要將上面dict中的coordinate中的經(jīng)緯度數(shù)據(jù)取出來存為x、y數(shù)據(jù),則可以按照下面的方法(此方法還可以調(diào)整每個(gè)屬性顯示的順序,效果更好一點(diǎn)):    
import csv
import json
import sys
import codecs
def trans(path):
 jsonData = codecs.open(path+'.json', 'r', 'utf-8')
 # csvfile = open(path+'.csv', 'w') # 此處這樣寫會導(dǎo)致寫出來的文件會有空行
 # csvfile = open(path+'.csv', 'wb') # python2下
 csvfile = open(path+'.csv', 'w', newline='') # python3下
 writer = csv.writer(csvfile, delimiter='\t')
 keys=['id', 'name', 'category', 'price', 'count', 'type', 'address', 'link', 'x', 'y']
 writer.writerow(keys)
 i = 1
 for dic in jsonData:
  dic = json.loads(dic[0:-1])
  x = dic['coordinates'][0]
  y = dic['coordinates'][1]
  writer.writerow([str(i),dic['name'],dic['category'],dic['price'],dic['count'],dic['type'],dic['address'],dic['link'],x,y])
  i += 1
 jsonData.close()
 csvfile.close()
if __name__ == '__main__':
 path = str(sys.argv[1])
 print (path)
 trans(path)

運(yùn)行方法同上。

json文件是我在大眾點(diǎn)評抓取的數(shù)據(jù),存儲格式為utf-8。建議使用codecs包來讀取json數(shù)據(jù),可指定編碼方式。    
jsonData = codecs.open(path + '.json', 'r', encoding='utf-8')
以上這篇利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法就是小編分享給大家的全部內(nèi)容了

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }