5 Get the city weather: Difference between revisions

From Banana Pi Wiki
Jump to navigation Jump to search
Line 17: Line 17:
  "weatherinfo":  
  "weatherinfo":  
  {
  {
  "city": "荆州",
  "city": "jingzhou",
  "cityid": "101200801",
  "cityid": "101200801",
  "img1": "n7.gif",
  "img1": "n7.gif",
Line 24: Line 24:
  "temp1": "16℃",
  "temp1": "16℃",
  "temp2": "23℃",
  "temp2": "23℃",
  "weather": "小雨转阴"
  "weather": "Rain turns shade"
  }
  }
  }
  }
Line 37: Line 37:
  url = "http://www.weather.com.cn/data/cityinfo/101200801.html"
  url = "http://www.weather.com.cn/data/cityinfo/101200801.html"
  rsp = urequests.get(url)
  rsp = urequests.get(url)
  data = eval(rsp.text) # eval函数用于把字符串类型的json数据->转为python的字典类型
  data = eval(rsp.text) # eval function is used to convert string type json data from -> to python dictionary type
  weather = data["weatherinfo"]
  weather = data["weatherinfo"]
  L = weather["temp1"] #最低温
  L = weather["temp1"] #lowest temperature
  H = weather["temp2"] #最高温
  H = weather["temp2"] #the highest temperature
  return "L:" + L[:-1] + " H:" + H[:-1] # 数据样例->  L:16 H:23
  return "L:" + L[:-1] + " H:" + H[:-1] #Data sample->  L:16 H:23
   
   
  display.scroll(get_weather())
  display.scroll(get_weather())
   
   
  # L[:-1] H[:-1]去掉℃和℉两个特殊符号,否则会出现编码错误
  # L[:-1] H[:-1]Remove ℃ ℉ and two special symbol, can appear otherwise coding errors

Revision as of 04:34, 24 February 2019

The development of preparation

  • 1. First, ensure the integrity of the current firmware dependency package
help(“modules”)
  • The effect is shown below. If you do not have two dependency packages on the diagram, please burn the latest firmware.

Prepare the weather API

{
"weatherinfo": 
{
"city": "jingzhou",
"cityid": "101200801",
"img1": "n7.gif",
"img2": "d2.gif",
"ptime": "18:00",
"temp1": "16℃",
"temp2": "23℃",
"weather": "Rain turns shade"
}
}

We can analyze these json files and write an example like this

example analyse

import urequests
from microbit import * 

def get_weather():
	url = "http://www.weather.com.cn/data/cityinfo/101200801.html"
	rsp = urequests.get(url)
	data = eval(rsp.text) # eval function is used to convert string type json data from -> to python dictionary type
	weather = data["weatherinfo"]
	L = weather["temp1"] #lowest temperature
	H = weather["temp2"] #the highest temperature
	return "L:" + L[:-1] + " H:" + H[:-1] #Data sample->  L:16 H:23

display.scroll(get_weather())

# L[:-1] H[:-1]Remove ℃ ℉ and two special symbol, can appear otherwise coding errors