《Python编程从入门到实践》学习笔记详解-项目篇(下载数据)

上两篇文章分别介绍了《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两种格式的数据。

猜你喜欢

转载自blog.csdn.net/zhang__shuang_/article/details/81835421
今日推荐