本文介绍了使用Python处理JSON及CSV文件的方法。首先展示了如何从JSON文件中提取2010年的各国人口数据并利用国别码进行展示其次通过一个CSV文件案例演示了如何读取气象数据并绘制成易于理解的图表。1、Python3处理json文件12345678910111213141516The i18n module was removed in pygal-2.0.0.however, it can now be found in the pygal_maps_world plugin.You can install that with pip install pygal_maps_world.Then you can access COUNTRIES as pygal.maps.world.COUNTRIES:from pygal.maps.world import COUNTRIESWhats left of the i18n module can be imported with:from pygal_maps_world import i18n#获取两个字母的国别码frompygal_maps_world.i18nimportCOUNTRIESdefget_country_code(country_name):forcode,nameinCOUNTRIES.items():ifnamecountry_name:returncodereturnNone12345678910111213141516importjsonfromCountry_codesimportget_country_code#提取相关数据filenamepopulation_data.jsonwithopen(filename) as f:pop_datajson.load(f)#json.load()将数据转换为Python能够处理的格式并存储在pop_data中forpop_dictinpop_data:#获得每个国家2010年的人口数量ifpop_dict[Year]2010:country_namepop_dict[Country Name]populationint(float(pop_dict[Value]))#先将字符串转换为浮点数再将浮点数转换为整数codeget_country_code(country_name)#获得国家的国别码ifcode:print(code:str(population))else:print(ERROR-country_name)2、Python3处理csv文件12345678910111213141516171819202122232425262728importcsvfrommatplotlibimportpyplot as pltfromdatetimeimportdatetime#读取CSV文件数据filenamesitka_weather_2014.csvwithopen(filename) as f:#打开这个文件并将结果文件对象存储在f中readercsv.reader(f)#创建一个阅读器readerheader_rownext(reader)#返回文件中的下一行dates,highs,lows[],[],[]#声明存储日期最值的列表forrowinreader:current_datedatetime.strptime(row[0],%Y-%m-%d)#将日期数据转换为datetime对象dates.append(current_date)#存储日期highint(row[1])#将字符串转换为数字highs.append(high)#存储温度最大值lowint(row[3])lows.append(low)#存储温度最小值#根据数据绘制图形figplt.figure(dpi128,figsize(10,6))plt.plot(dates,highs,cred,alpha0.5)#实参alpha指定颜色的透明度0表示完全透明1默认值完全不透明plt.plot(dates,lows,cblue,alpha0.5)plt.fill_between(dates,highs,lows,facecolorblue,alpha0.1)#给图表区域填充颜色plt.title(Daily high and low temperature-2004,fontsize24)plt.xlabel(,fontsize16)plt.ylabel(Temperature(F),fontsize16)plt.tick_params(axisboth,whichmajor,labelsize16)fig.autofmt_xdate()#绘制斜的日期标签plt.show()结果如下3、方法补充Python3处理JSON格式的文件数据下面介绍了一种从世界地图插件中获取国别码的方法并演示了如何使用Python从JSON文件中提取指定年份的各国人口数据。通过安装pygal_maps_world插件并利用其i18n模块中的COUNTRIES字典来匹配国家名称与其对应的两字母国别码。Country_code.py12345678910111213141516The i18n module was removed in pygal-2.0.0.however, it can now be found in the pygal_maps_world plugin.You can install that with pip install pygal_maps_world.Then you can access COUNTRIES as pygal.maps.world.COUNTRIES:from pygal.maps.world import COUNTRIESWhats left of the i18n module can be imported with:from pygal_maps_world import i18n#获取两个字母的国别码frompygal_maps_world.i18nimportCOUNTRIESdefget_country_code(country_name):forcode,nameinCOUNTRIES.items():ifnamecountry_name:returncodereturnNonePopulation.py12345678910111213141516importjsonfromCountry_codesimportget_country_code#提取相关数据filenamepopulation_data.jsonwithopen(filename) as f:pop_datajson.load(f)#json.load()将数据转换为Python能够处理的格式并存储在pop_data中forpop_dictinpop_data:#获得每个国家2010年的人口数量ifpop_dict[Year]2010:country_namepop_dict[Country Name]populationint(float(pop_dict[Value]))#先将字符串转换为浮点数再将浮点数转换为整数codeget_country_code(country_name)#获得国家的国别码ifcode:print(code:str(population))else:print(ERROR-country_name)Python将CSV文件如何转JSON文件CSV文件CSVComma-Separated Values逗号分隔的值是一种简单、实用的文件格式用于存储和表示包括文本、数值等各种类型的数据。CSV 文件通常以 .csv 作为文件扩展名。这种文件格式的一个显著特点是文件内的数据以逗号 , 分隔呈现一个表格形式。CSV 文件已广泛应用于存储、传输和编辑数据。JSON文件JSON 指的是 JavaScript 对象表示法JavaScript Object NotationJSON是轻量级的文本数据交换格式 JSON 独立于语言JSON 使用 Javascript语法来描述数据对象但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态PHPJSP.NET编程语言都支持JSON。实现方法123456789101112131415161718192021222324252627282930313233importjsonfopen(D:/文件/资料/GT.csv,r, encodingGB2312)# csv文件的路径data_linesf.readlines()f.close()data_lines.pop(0)values[]forlineindata_lines:lineline.replace(\n, )values.append(line.split(,))# print(ls)# json文件为键值对keys为左侧键keys[stamp_sec,obj_stamp_sec,frame_num,source,id,track_id,lane_id,center_x,center_y,center_z,closest_point_x,closest_point_y,closest_point_z,closest_box_x,closest_box_y,closest_box_z,front_bumper_x,front_bumper_y,front_bumper_z,rear_bumper_x,rear_bumper_y,rear_bumper_z,move_status,cut_in,cut_out,cipv,velocity_x,velocity_y,velocity_z,project_velocity_x,project_velocity_y,project_velocity_z,acceleration_x,acceleration_y,acceleration_z,project_acceleration_x,project_acceleration_y,project_acceleration_z,angular_velocity,obj_yaw,direction_x,direction_y,direction_z,height,length,width,is_radar_matching,is_tracked,radar_velocity_x,radar_velocity_y,radar_velocity_z,type,type_confidence,pose_pos_x,pose_pos_y,pose_pos_z,roll,pitch,yaw,car_twist,car_acceleration,reserve_score,reserve_info,anchor_x,anchor_y,anchor_z,lidar_name]fwopen(D:/文件/资料/a.json,w, encodingutf-8)# 创建json文件的路径# 利用for循环遍历形成键值对dict_re[dict(zip(keys, row))forrowinvalues]ifvalueselseNone# print(dict_re)ajson.dumps(dict_re, indent4, ensure_asciiFalse)print(a)fw.write(a)fw.close()到此这篇关于Python3处理json文件和csv文件的文章就介绍到这了