TangBean
9/27/2017 - 1:15 PM

Ch.16 处理 csv 和 json 数据

Ch.16 处理 csv 和 json 数据

import json

filename = 'population_data.json'
with open(filename) as f:
    # pop_data is a dictionary
    pop_data = json.load(f)

for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = pop_dict['Value']

        # Change population string to int, need to change to float first
        population_int = int(float(population))
        print(country_name + ': ' + population)
        print('Int Population = ', population_int)

说明

csv.reader(f)
json.load(f)
import csv
from matplotlib import pyplot as plt
from datetime import datetime
import numpy as np

filename = 'sitka_weather_2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    highs, dates, lows = [], [], []
    for row in reader:
        current_date = datetime.strptime(row[0], '%Y-%m-%d')
        dates.append(current_date)
        highs.append(row[1])
        lows.append(row[2])

fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)

fig.autofmt_xdate()
plt.title("Daily high and low temperatures - 2014", fontsize=24)

plt.show()