首頁>技術>

原文地址: https://segmentfault.com/a/1190000038683437

先看下效果圖:

用到的模組:

PyMySQLrequeststhreadingwxpy

要實現上面的示例,首先是有兩大塊地方

獲取天氣資訊 獲取天氣資訊的介面 獲取天氣資訊的城市 獲取所在城市的城市碼

假如我們給多個人傳送天氣情況,這幾個人來自不同的城市,那麼我們不可能每次都要輸入城市名,然後查詢城市碼,然後再訪問介面,獲取天氣情況,這樣會非常的麻煩,所以我們需要考慮將城市名跟城市碼一一對應起來,說到一一對應,首先想到的資料結構便是字典,所以我們可以將這些資訊存入一個字典裡,然後持久化到一個檔案中,這樣便方便很多

首先我們獲取最新的 city 表,這個表是一個 list 型別,大體格式如下:

我們就簡單的貼上複製,放到一個空的列表中,如下所示,將所有的城市資訊放到列表 citycode 中

citycode = [  {    "id": 1,    "pid": 0,    "city_code": "101010100",    "city_name": "北京",    "post_code": "100000",    "area_code": "010",    "ctime": "2019-07-11 17:30:06"  },..................  {    "id": 2,    "pid": 0,    "city_code": "None",    "city_name": "安徽",    "post_code": "null",    "area_code": "null",    "ctime": "null"  }]cityinfo = {}#將城市名和城市程式碼寫入json檔案中with open('city_for_code.json','w',encoding='utf-8') as f:    for i in citycode:        name = i["city_name"]        code = i["city_code"]        cityinfo[name] = code    f.write(str(cityinfo))#測試是否能讀取with open('city_for_code.json','r+',encoding='utf-8') as file:    data_dst = file.readlines()    d = eval(data_dst[0])

然後就是一頓處理,只把我們所需的 city_name 和 city_code 這倆欄位取出即可,隨後寫入檔案中。如果讀取的話就按照上面方法去讀取,需要注意的是,使用 open()方法讀取檔案,得到的內容是一個列表,我們需要透過 eval()方法轉化成 dict 型別。

這是把 city_name 和 city_code 放到一個檔案中的方法,另外我們也可以放到資料庫中,這裡以 MySQL 為例,安裝 PyMySQL 模組

import pymysqldb_parames = {    'host': 'localhost',    'user': 'root',    'password': '123456',    'database': 'city_code_info'}#連線資料庫conn = pymysql.connect(**db_parames)#建立遊標物件,增刪改查都在遊標上進行cursor = conn.cursor()#表存在,就刪除cursor.execute("DROP TABLE IF EXISTS city_code")#建表語句create_table_sql = """CREATE TABLE `city_code` (  `city_name` varchar(20) DEFAULT NULL,  `city_code` varchar(25) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"""#建表cursor.execute(create_table_sql)#插入資料with open('city_for_code.json','r+',encoding='utf-8') as f:    origin_data = f.readlines()    current_data = eval(origin_data[0])   #讀取的內容是一個列表,且只包含一個元素    #print(current_data.get('北京','Not Exists.'))    for name, code in current_data.items():        sql = """INSERT INTO city_code(city_name, city_code) VALUES ('%s', '%s')""" % (name, code)        try:            cursor.execute(sql)        except:            conn.rollback()    conn.commit()    conn.close()

執行這個 python 程式就可以將檔案中的城市名跟城市碼存到庫中,當然我們也可以直接獲取到城市名和城市碼,然後跳過檔案持久化這一步,直接把這兩個欄位取出存進去,但是考慮著程式碼要多練多寫,就多此一舉了一下。

下面是輸入城市名就能得到城市碼的程式碼塊:

import pymysqldef get_city_code(city_name):    db_parames = {    'host': 'localhost',    'user': 'root',    'password': '123456',    'database': 'city_code_info'    }    #連線資料庫    conn = pymysql.connect(**db_parames)    #建立遊標物件,增刪改查都在遊標上進行    cursor = conn.cursor()    #建立查詢語句    select_sql = "SELECT * FROM city_code where city_name='%s'"%(city_name)    try:        cursor.execute(select_sql)        result = cursor.fetchall()        for row in result:            city_code = row[1]        return city_code    except:        return "Error: unable fetch data!"

然後是根據輸入的城市碼來獲取天氣情況:

import requestsdef get_weather(city_name,get_date_time=3):    city_code = get_city_code(city_name)    url = 'http://t.weather.sojson.com/api/weather/city/%s'%(city_code)    header = {    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'    }    response = requests.get(url,header)    response.encoding = 'utf-8'    weather = response.json()    day = {1: '明天', 2: '後天', 3: '大後天'}    weather_lst = []    for num in range(get_date_time):        City = weather["cityInfo"]["city"]        Weatherganmao = weather["data"]["ganmao"]        Weatherquality = weather["data"]["quality"]        Weathershidu = weather["data"]["shidu"]        Weatherwendu = weather["data"]["wendu"]        Weatherpm25 = str(weather["data"]["pm25"])        Weatherpm10 = str(weather["data"]["pm10"])        Dateymd = weather["data"]["forecast"][num]["ymd"]        Dateweek = weather["data"]["forecast"][num]["week"]        Sunrise = weather["data"]["forecast"][num]["sunrise"]        Sunset = weather["data"]["forecast"][num]["sunset"]        Windfx = weather["data"]["forecast"][num]["fx"]        Windf1 = weather["data"]["forecast"][num]["fl"]        Weathertype = weather["data"]["forecast"][num]["type"]        Weathernotice = weather["data"]["forecast"][num]["notice"]        Weatherhigh = weather["data"]["forecast"][num]["high"]        Weatherlow = weather["data"]["forecast"][num]["low"]        if num == 0:            result = '今日天氣預報' + '\n' \                + '日期: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \                + '天氣: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \                + '當前溫度: ' + Weatherwendu + '℃' + '\n' \                + '空氣溼度: ' + Weathershidu + '\n' \                + '溫度範圍: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \                + '汙染指數: ' + 'PM2.5: ' + Weatherpm25 + ' ' + 'PM10: ' + Weatherpm10 + '\n' \                + '空氣質量: ' + Weatherquality + '\n' \                + '日出時間: ' + Sunrise + '\n' \                + '日落時間: ' + Sunset + '\n' \                + '溫馨提示: ' + Weatherganmao        else:            which_day = day.get(num,'超出範圍')            result = '\n' + which_day + ' ' + '天氣預報' + '\n' \                + '日期: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \                + '天氣: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \                + '溫度範圍: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \                + '日出時間: ' + Sunrise + '\n' \                + '日落時間: ' + Sunset + '\n' \                + '溫馨提示: ' + Weatherganmao        weather_lst.append(result)        weather_str = ''     #因為預設要輸出三天的天氣情況,所以我們需要建立一個空字串,然後每迭代一次,就將天氣情況拼接到空字串中。        for msg in weather_lst:            weather_str += msg + '\n'    return weather_str

下面是傳送微信訊息

然後我們還需要寫一個定時器,每隔一段時間便要傳送一次

最後執行程式

8
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • 乾貨滿滿:三種Python排序