最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python3處理json文件和csv文件

 更新時間:2026年01月07日 09:31:02   作者:Asia-Lee  
這篇文章主要為大家詳細(xì)介紹了Python3處理json文件和csv文件的相關(guān)方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

本文介紹了使用Python處理JSON及CSV文件的方法。首先展示了如何從JSON文件中提取2010年的各國人口數(shù)據(jù)并利用國別碼進(jìn)行展示;其次通過一個CSV文件案例,演示了如何讀取氣象數(shù)據(jù)并繪制成易于理解的圖表。

1、Python3處理json文件

'''
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
import json
from Country_codes import get_country_code
#提取相關(guān)數(shù)據(jù)
filename='population_data.json'
with open(filename) as f:
    pop_data=json.load(f) #json.load()將數(shù)據(jù)轉(zhuǎn)換為Python能夠處理的格式并存儲在pop_data中
    for pop_dict in pop_data:
        #獲得每個國家2010年的人口數(shù)量
        if pop_dict['Year']=='2010':
            country_name=pop_dict['Country Name']
            population=int(float(pop_dict['Value']))#先將字符串轉(zhuǎn)換為浮點(diǎn)數(shù),再將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)
            code=get_country_code(country_name)  #獲得國家的國別碼
            if code:
                print(code+':'+str(population))
            else:
                print('ERROR-'+country_name)

2、Python3處理csv文件

import csv
from matplotlib import pyplot as plt
from datetime import datetime
#讀取CSV文件數(shù)據(jù)
filename='sitka_weather_2014.csv'
with open(filename) as f: #打開這個文件,并將結(jié)果文件對象存儲在f中
    reader=csv.reader(f)  #創(chuàng)建一個閱讀器reader
    header_row=next(reader) #返回文件中的下一行
    dates,highs,lows=[],[],[]      #聲明存儲日期,最值的列表
    for row in reader:
        current_date=datetime.strptime(row[0],'%Y-%m-%d')  #將日期數(shù)據(jù)轉(zhuǎn)換為datetime對象
        dates.append(current_date)    #存儲日期
        high=int(row[1])    #將字符串轉(zhuǎn)換為數(shù)字
        highs.append(high)   #存儲溫度最大值
        low=int(row[3])
        lows.append(low)    #存儲溫度最小值

#根據(jù)數(shù)據(jù)繪制圖形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)#實(shí)參alpha指定顏色的透明度,0表示完全透明,1(默認(rèn)值)完全不透明
plt.plot(dates,lows,c='blue',alpha=0.5)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1) #給圖表區(qū)域填充顏色
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()  #繪制斜的日期標(biāo)簽
plt.show()

結(jié)果如下:

3、方法補(bǔ)充

Python3處理JSON格式的文件數(shù)據(jù)

下面介紹了一種從世界地圖插件中獲取國別碼的方法,并演示了如何使用Python從JSON文件中提取指定年份的各國人口數(shù)據(jù)。通過安裝pygal_maps_world插件并利用其i18n模塊中的COUNTRIES字典來匹配國家名稱與其對應(yīng)的兩字母國別碼。

Country_code.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

Population.py

import json
from Country_codes import get_country_code
#提取相關(guān)數(shù)據(jù)
filename='population_data.json'
with open(filename) as f:
    pop_data=json.load(f) #json.load()將數(shù)據(jù)轉(zhuǎn)換為Python能夠處理的格式并存儲在pop_data中
    for pop_dict in pop_data:
        #獲得每個國家2010年的人口數(shù)量
        if pop_dict['Year']=='2010':
            country_name=pop_dict['Country Name']
            population=int(float(pop_dict['Value']))#先將字符串轉(zhuǎn)換為浮點(diǎn)數(shù),再將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)
            code=get_country_code(country_name)  #獲得國家的國別碼
            if code:
                print(code+':'+str(population))
            else:
                print('ERROR-'+country_name)

Python將CSV文件如何轉(zhuǎn)JSON文件

CSV文件:CSV(Comma-Separated Values,逗號分隔的值)是一種簡單、實(shí)用的文件格式,用于存儲和表示包括文本、數(shù)值等各種類型的數(shù)據(jù)。CSV 文件通常以 .csv 作為文件擴(kuò)展名。這種文件格式的一個顯著特點(diǎn)是:文件內(nèi)的數(shù)據(jù)以逗號 , 分隔,呈現(xiàn)一個表格形式。CSV 文件已廣泛應(yīng)用于存儲、傳輸和編輯數(shù)據(jù)。

JSON文件:JSON 指的是 JavaScript 對象表示法(JavaScript Object Notation),JSON是輕量級的文本數(shù)據(jù)交換格式 JSON 獨(dú)立于語言:JSON 使用 Javascript語法來描述數(shù)據(jù)對象,但是 JSON 仍然獨(dú)立于語言和平臺。JSON 解析器和 JSON 庫支持許多不同的編程語言。 目前非常多的動態(tài)(PHP,JSP,.NET)編程語言都支持JSON。

實(shí)現(xiàn)方法

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為左側(cè)鍵
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') # 創(chuàng)建json文件的路徑

# 利用for循環(huán)遍歷,形成鍵值對
dict_re = [dict(zip(keys, row)) for row in values] if values else None 
# print(dict_re)
a = json.dumps(dict_re, indent=4, ensure_ascii=False)
print(a)
fw.write(a)
fw.close()

到此這篇關(guān)于Python3處理json文件和csv文件的文章就介紹到這了,更多相關(guān)Python處理json和csv內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Pytorch中expand()的使用(擴(kuò)展某個維度)

    Pytorch中expand()的使用(擴(kuò)展某個維度)

    這篇文章主要介紹了Pytorch中expand()的使用(擴(kuò)展某個維度),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Python機(jī)器學(xué)習(xí)應(yīng)用之基于LightGBM的分類預(yù)測篇解讀

    Python機(jī)器學(xué)習(xí)應(yīng)用之基于LightGBM的分類預(yù)測篇解讀

    這篇文章我們繼續(xù)學(xué)習(xí)一下GBDT模型的另一個進(jìn)化版本:LightGBM,LigthGBM是boosting集合模型中的新進(jìn)成員,由微軟提供,它和XGBoost一樣是對GBDT的高效實(shí)現(xiàn),原理上它和GBDT及XGBoost類似,都采用損失函數(shù)的負(fù)梯度作為當(dāng)前決策樹的殘差近似值,去擬合新的決策樹
    2022-01-01
  • NumPy隨機(jī)數(shù)生成函數(shù)的多種實(shí)現(xiàn)方法

    NumPy隨機(jī)數(shù)生成函數(shù)的多種實(shí)現(xiàn)方法

    NumPy的numpy.random模塊提供了多種隨機(jī)數(shù)生成函數(shù),包括基礎(chǔ)隨機(jī)數(shù)生成、概率分布抽樣和隨機(jī)排列,這些函數(shù)適用于各種場景,下面就來詳細(xì)的介紹一下,感興趣的可以了解一下
    2026-01-01
  • python數(shù)據(jù)分析近年比特幣價格漲幅趨勢分布

    python數(shù)據(jù)分析近年比特幣價格漲幅趨勢分布

    這篇文章主要為大家介紹了python分析近年來比特幣價格漲幅趨勢的數(shù)據(jù)分布,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-11-11
  • 使用Python實(shí)現(xiàn)跳幀截取視頻幀

    使用Python實(shí)現(xiàn)跳幀截取視頻幀

    這篇文章主要介紹了使用Python實(shí)現(xiàn)跳幀截取視頻幀,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Pandas中datetime數(shù)據(jù)類型的使用

    Pandas中datetime數(shù)據(jù)類型的使用

    本文主要介紹了Pandas中datetime數(shù)據(jù)類型的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-12-12
  • Python實(shí)現(xiàn)在PDF中插入單圖像水印和平鋪圖像水印

    Python實(shí)現(xiàn)在PDF中插入單圖像水印和平鋪圖像水印

    這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)在PDF中插入單圖像水印和平鋪圖像水印,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-04-04
  • Python的f-string使用技巧

    Python的f-string使用技巧

    Python很早就引入了一種稱為 f-string 的字符串格式化方法,它代表格式化字符串字面值,本文主要介紹了Python的f-string使用技巧,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Python實(shí)現(xiàn)微信中找回好友、群聊用戶撤回的消息功能示例

    Python實(shí)現(xiàn)微信中找回好友、群聊用戶撤回的消息功能示例

    這篇文章主要介紹了Python實(shí)現(xiàn)微信中找回好友、群聊用戶撤回的消息功能,結(jié)合實(shí)例形式分析了Python基于微信itchat模塊實(shí)現(xiàn)針對撤回消息的查看功能相關(guān)操作技巧,需要的朋友可以參考下
    2019-08-08
  • Python列表1~n輸出步長為3的分組實(shí)例

    Python列表1~n輸出步長為3的分組實(shí)例

    這篇文章主要介紹了Python列表1~n輸出步長為3的分組實(shí)例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05

最新評論

中宁县| 孟津县| 常山县| 永登县| 高青县| 师宗县| 平顺县| 法库县| 桦甸市| 巴林右旗| 文昌市| 吉木萨尔县| 成安县| 白沙| 中阳县| 昭平县| 水城县| 阿拉尔市| 宁津县| 嫩江县| 襄樊市| 黄浦区| 建水县| 防城港市| 资中县| 吴桥县| 西平县| 嘉祥县| 桂东县| 怀远县| 德清县| 明光市| 武义县| 麻城市| 临武县| 涞源县| 莲花县| 宣威市| 十堰市| 桂阳县| 曲阜市|