熙落人间 發表於 2026-1-7 09:31:02

Python3处理json文件和csv文件

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">1、Python3处理json文件</a></li><li><a href="#_label1">2、Python3处理csv文件</a></li><li><a href="#_label2">3、方法补充</a></li></ul></div><p>本文介绍了使用Python处理JSON及CSV文件的方法。首先展示了如何从JSON文件中提取2010年的各国人口数据并利用国别码进行展示;其次通过一个CSV文件案例,演示了如何读取气象数据并绘制成易于理解的图表。</p>
<p class="maodian"><a name="_label0"></a></p><h2>1、Python3处理json文件</h2>
<div class="jb51code"><pre class="brush:py;">'''
The 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 COUNTRIES
Whats left of the i18n module can be imported with:
from pygal_maps_world import i18n
'''
#获取两个字母的国别码
from pygal_maps_world.i18n import COUNTRIES
def get_country_code(country_name):
    for code,name in COUNTRIES.items():
      if name==country_name:
            return code
      return None</pre></div>
<div class="jb51code"><pre class="brush:py;">import json
from Country_codes import get_country_code
#提取相关数据
filename='population_data.json'
with open(filename) as f:
    pop_data=json.load(f) #json.load()将数据转换为Python能够处理的格式并存储在pop_data中
    for pop_dict in pop_data:
      #获得每个国家2010年的人口数量
      if pop_dict['Year']=='2010':
            country_name=pop_dict['Country Name']
            population=int(float(pop_dict['Value']))#先将字符串转换为浮点数,再将浮点数转换为整数
            code=get_country_code(country_name)#获得国家的国别码
            if code:
                print(code+':'+str(population))
            else:
                print('ERROR-'+country_name)</pre></div>
<p class="maodian"><a name="_label1"></a></p><h2>2、Python3处理csv文件</h2>
<div class="jb51code"><pre class="brush:py;">import csv
from matplotlib import pyplot as plt
from datetime import datetime
#读取CSV文件数据
filename='sitka_weather_2014.csv'
with open(filename) as f: #打开这个文件,并将结果文件对象存储在f中
    reader=csv.reader(f)#创建一个阅读器reader
    header_row=next(reader) #返回文件中的下一行
    dates,highs,lows=[],[],[]      #声明存储日期,最值的列表
    for row in reader:
      current_date=datetime.strptime(row,'%Y-%m-%d')#将日期数据转换为datetime对象
      dates.append(current_date)    #存储日期
      high=int(row)    #将字符串转换为数字
      highs.append(high)   #存储温度最大值
      low=int(row)
      lows.append(low)    #存储温度最小值

#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)#实参alpha指定颜色的透明度,0表示完全透明,1(默认值)完全不透明
plt.plot(dates,lows,c='blue',alpha=0.5)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1) #给图表区域填充颜色
plt.title('Daily high and low temperature-2004',fontsize=24)
plt.xlabel('',fontsize=16)
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
fig.autofmt_xdate()#绘制斜的日期标签
plt.show()</pre></div>
<p>结果如下:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202601/2026010709262654.png" /></p>
<p class="maodian"><a name="_label2"></a></p><h2>3、方法补充</h2>
<p><strong>Python3处理JSON格式的文件数据</strong></p>
<p>下面介绍了一种从世界地图插件中获取国别码的方法,并演示了如何使用Python从JSON文件中提取指定年份的各国人口数据。通过安装pygal_maps_world插件并利用其i18n模块中的COUNTRIES字典来匹配国家名称与其对应的两字母国别码。</p>
<p><strong>Country_code.py</strong></p>
<div class="jb51code"><pre class="brush:py;">'''
The 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 COUNTRIES
Whats left of the i18n module can be imported with:
from pygal_maps_world import i18n
'''
#获取两个字母的国别码
from pygal_maps_world.i18n import COUNTRIES
def get_country_code(country_name):
    for code,name in COUNTRIES.items():
      if name==country_name:
            return code
      return None</pre></div>
<p><strong>Population.py</strong></p>
<div class="jb51code"><pre class="brush:py;">import json
from Country_codes import get_country_code
#提取相关数据
filename='population_data.json'
with open(filename) as f:
    pop_data=json.load(f) #json.load()将数据转换为Python能够处理的格式并存储在pop_data中
    for pop_dict in pop_data:
      #获得每个国家2010年的人口数量
      if pop_dict['Year']=='2010':
            country_name=pop_dict['Country Name']
            population=int(float(pop_dict['Value']))#先将字符串转换为浮点数,再将浮点数转换为整数
            code=get_country_code(country_name)#获得国家的国别码
            if code:
                print(code+':'+str(population))
            else:
                print('ERROR-'+country_name)</pre></div>
<p><strong>Python将CSV文件如何转JSON文件</strong></p>
<p><strong>CSV文件:</strong>CSV(Comma-Separated Values,逗号分隔的值)是一种简单、实用的文件格式,用于存储和表示包括文本、数值等各种类型的数据。CSV 文件通常以 .csv 作为文件扩展名。这种文件格式的一个显著特点是:文件内的数据以逗号 , 分隔,呈现一个表格形式。CSV 文件已广泛应用于存储、传输和编辑数据。</p>
<p><strong>JSON文件:</strong>JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation),JSON是轻量级的文本数据交换格式 JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。</p>
<p><strong>实现方法</strong></p>
<div class="jb51code"><pre class="brush:py;">import json

f = open("D:/文件/资料/GT.csv", "r", encoding='GB2312') # csv文件的路径
data_lines = f.readlines()
f.close()
data_lines.pop(0)

values = []
for line in data_lines:
    line = line.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"]

fw = open("D:/文件/资料/a.json", "w", encoding='utf-8') # 创建json文件的路径

# 利用for循环遍历,形成键值对
dict_re = if values else None
# print(dict_re)
a = json.dumps(dict_re, indent=4, ensure_ascii=False)
print(a)
fw.write(a)
fw.close()</pre></div>
頁: [1]
查看完整版本: Python3处理json文件和csv文件