『Pythonプログラミング入門から実践へ』学習ノート詳細-プロジェクト編(ダウンロードデータ)

3178 ワード

前の2つの文章はそれぞれ《Pythonプログラミングは入門から実践まで》の文法編とプロジェクト編(データの可視化)を紹介して、この文
#        
#      csv json            



#csv



#       
import csv
filename='filename.csv'
with open(filename) as f:
    reader=csv.reader(f)
    #       
    header_row=next(reader)
    highs=[]
    for row in reader:
        highs.append(row[1])
    #           ,              
    for row in reader:
        high=int (row[1])
        highs.append(high)
    #    '2014-7-1'              
    #datetime  
    '''
    %A       
    %B      
    %m           
    %d              
    %Y        
    %y        
    %H   24       
    %I   12       
    %p   am pm
    %M      
    %S     
    '''
    from datetime import datetime
    first_data=datatime.strptime('2014-7-1','%Y-%m-%d')
    
    
#        
filename='filename.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)
    
    dates,highs,lows=[],[],[]
    for row in reader:
        current_date=datetime_strptime(row[0],'%Y-%m-%d')
        dates.append(current_date)
        
        high=int(row[1])
        highs.append(high)
        
        low=int(row[3])
        lows.append(low)
        
fig=plt.figure(dpi=128,figsize=(10,6))
#alpha        ,alpha 0      ,   1
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c='blue')
#         ,              
fig.autofmt_xdate()
# lows highs       
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)
  

# csv          null     ,          :
for row in reader:
    try:
        current_date=datetime.strptime(row[0],'%Y-%m-%d')
        high=int (row[1])
        low=int(row[3])
    except ValueError:
        print(current_date,'missing data')
    else:
        dates.append(current_date)
        highs.append(high)
        lows.append(low)
    
    

#json
        
        
        
#json    
        '''
        [{'country name':'Arab world',
          'country code':'ARB',
          'Year':'1960'
          'Value':'96388069'
        }
        ]
        '''
import json
filename='population.json'
with open(filename) as f:
    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']
        print(country_name+":"+population)
    
    
#      
import pygal
wm=pygal.Worldmap()
wm.title='North,Central,and SouthAmerica'
#          
wm.add('North America',{'ca':3412600,'mx':113423000,'us':309349000})
wm.add('Central America',['bz','cr','gt','hn','ni','pa','sv'])
wm.add('South America',['ar','bo','br','cl','co','ec','gf','gy','pe','sr','uy','ve'])
print(wm)
        
        
        


            

章では、プロジェクト編のcsvとjsonの2つのフォーマットのデータのダウンロードについて説明します.