#提取并读取数据 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)