欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python獲取天氣接口給指定微信好友發(fā)天氣預(yù)報

 更新時間:2020年12月28日 10:59:17   作者:dogfei  
這篇文章主要介紹了python獲取天氣接口給指定微信好友發(fā)天氣預(yù)報的步驟,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下

先看下效果圖:

用到的模塊:

  • PyMySQL
  • requests
  • threading
  • wxpy

要實現(xiàn)上面的示例,首先是有兩大塊地方

  • 獲取天氣信息
  • 通過微信將天氣信息發(fā)送出去

而獲取天氣信息又包括幾個小的需要注意的地方

獲取天氣信息

  • 獲取天氣信息的接口
  • 獲取天氣信息的城市
  • 獲取所在城市的城市碼

假如我們給多個人發(fā)送天氣情況,這幾個人來自不同的城市,那么我們不可能每次都要輸入城市名,然后查找城市碼,然后再訪問接口,獲取天氣情況,這樣會非常的麻煩,所以我們需要考慮將城市名跟城市碼一一對應(yīng)起來,說到一一對應(yīng),首先想到的數(shù)據(jù)結(jié)構(gòu)便是字典,所以我們可以將這些信息存入一個字典里,然后持久化到一個文件中,這樣便方便很多

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

[
 {
  "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": "",
  "city_name": "安徽",
  "post_code": null,
  "area_code": null,
  "ctime": null
 }
]

我們就簡單的粘貼復(fù)制,放到一個空的列表中,如下所示,將所有的城市信息放到列表 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()方法讀取文件,得到的內(nèi)容是一個列表,我們需要通過 eval()方法轉(zhuǎn)化成 dict 類型。

這是把 city_name 和 city_code 放到一個文件中的方法,另外我們也可以放到數(shù)據(jù)庫中,這里以 MySQL 為例,安裝 PyMySQL 模塊

import pymysql

db_parames = {
  'host': 'localhost',
  'user': 'root',
  'password': '123456',
  'database': 'city_code_info'
}
#連接數(shù)據(jù)庫
conn = pymysql.connect(**db_parames)

#創(chuàng)建游標對象,增刪改查都在游標上進行
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)

#插入數(shù)據(jù)
with open('city_for_code.json','r+',encoding='utf-8') as f:
  origin_data = f.readlines()
  current_data = eval(origin_data[0])  #讀取的內(nèi)容是一個列表,且只包含一個元素
  #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()

執(zhí)行這個 python 程序就可以將文件中的城市名跟城市碼存到庫中,當然我們也可以直接獲取到城市名和城市碼,然后跳過文件持久化這一步,直接把這兩個字段取出存進去,但是考慮著代碼要多練多寫,就多此一舉了一下。

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

import pymysql

def get_city_code(city_name):
  db_parames = {
  'host': 'localhost',
  'user': 'root',
  'password': '123456',
  'database': 'city_code_info'
  }
  #連接數(shù)據(jù)庫
  conn = pymysql.connect(**db_parames)

  #創(chuàng)建游標對象,增刪改查都在游標上進行
  cursor = conn.cursor()

  #創(chuàng)建查詢語句
  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!"

然后是根據(jù)輸入的城市碼來獲取天氣情況:

import requests

def 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 = '今日天氣預(yù)報' + '\n' \
        + '日期: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \
        + '天氣: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \
        + '當前溫度: ' + Weatherwendu + '℃' + '\n' \
        + '空氣濕度: ' + Weathershidu + '\n' \
        + '溫度范圍: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \
        + '污染指數(shù): ' + 'PM2.5: ' + Weatherpm25 + ' ' + 'PM10: ' + Weatherpm10 + '\n' \
        + '空氣質(zhì)量: ' + Weatherquality + '\n' \
        + '日出時間: ' + Sunrise + '\n' \
        + '日落時間: ' + Sunset + '\n' \
        + '溫馨提示: ' + Weatherganmao
    else:
      which_day = day.get(num,'超出范圍')
      result = '\n' + which_day + ' ' + '天氣預(yù)報' + '\n' \
        + '日期: ' + Dateymd + ' ' + Dateweek + ' ' + City + '\n' \
        + '天氣: ' + Weathertype + ' ' + Windfx + ' ' + Windf1 + ' ' + Weathernotice + '\n' \
        + '溫度范圍: ' + Weatherlow + '' + '~' + '' + Weatherhigh + '\n' \
        + '日出時間: ' + Sunrise + '\n' \
        + '日落時間: ' + Sunset + '\n' \
        + '溫馨提示: ' + Weatherganmao
    weather_lst.append(result)
    weather_str = ''   #因為默認要輸出三天的天氣情況,所以我們需要創(chuàng)建一個空字符串,然后每迭代一次,就將天氣情況拼接到空字符串中。
    for msg in weather_lst:
      weather_str += msg + '\n'

  return weather_str

下面是發(fā)送微信消息

from wxpy import *

def send_wx(city_name, who):
  bot = Bot(cache_path=True)
  #bot = Bot(console_qr=2, cache_path='botoo.pkl')
  my_friend = bot.friends().search(who)[0]
  msg = get_weather(city_name)
  try:
    my_friend.send(msg)
  except:
    my_friend = bot.friends().search('fei')[0]
    my_friend.send(u"發(fā)送失敗")

然后我們還需要寫一個定時器,每隔一段時間便要發(fā)送一次

from threading import Timer

def auto_send():
  city_name = '設(shè)置要發(fā)送的城市'
  friend_list = ['要發(fā)送的人']

  for who in friend_list:
    send_wx(city_name,who)
  global timer
  timer = Timer(1,auto_send)
  timer.start()

最后執(zhí)行程序

if __name__ == '__main__':
  timer = Timer(1,auto_send)
  timer.start()

以上就是python獲取天氣接口給指定微信好友發(fā)天氣預(yù)報的詳細內(nèi)容,更多關(guān)于python獲取天氣接口的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 4種方法教你利用Python發(fā)現(xiàn)數(shù)據(jù)的規(guī)律

    4種方法教你利用Python發(fā)現(xiàn)數(shù)據(jù)的規(guī)律

    發(fā)現(xiàn)數(shù)據(jù)的規(guī)律是數(shù)據(jù)分析和數(shù)據(jù)科學(xué)中非常重要的一個步驟。這篇文章主要給大家整理了4個可以發(fā)現(xiàn)數(shù)據(jù)規(guī)律的方法,希望對大家有所幫助
    2023-03-03
  • pytorch的梯度計算以及backward方法詳解

    pytorch的梯度計算以及backward方法詳解

    今天小編就為大家分享一篇pytorch的梯度計算以及backward方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python異常學(xué)習(xí)筆記

    Python異常學(xué)習(xí)筆記

    這篇文章主要介紹了Python異常學(xué)習(xí)筆記,本文著重講解了如何自定義一個異常,需要的朋友可以參考下
    2015-02-02
  • Python?time時間格式化操作指南

    Python?time時間格式化操作指南

    這篇文章主要給大家介紹了關(guān)于Python?time時間格式化操作的相關(guān)資料,Python中日期格式化是非常常見的操作,Python中能用很多方式處理日期和時間,轉(zhuǎn)換日期格式是一個常見的功能,需要的朋友可以參考下
    2023-10-10
  • 詳解一種用django_cache實現(xiàn)分布式鎖的方式

    詳解一種用django_cache實現(xiàn)分布式鎖的方式

    這篇文章主要介紹了詳解一種用django_cache實現(xiàn)分布式鎖的方式,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • python讀取.mat文件及將變量存為.mat文件的詳細介紹

    python讀取.mat文件及將變量存為.mat文件的詳細介紹

    這篇文章主要給大家介紹了關(guān)于python讀取.mat文件及將變量存為.mat文件的詳細介紹,?mat文件是matlab的數(shù)據(jù)存儲的標準格式,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-06-06
  • Tkinter組件Entry的具體使用

    Tkinter組件Entry的具體使用

    本文主要介紹了Tkinter組件Entry的具體使用,Entry組件通常用于獲取用戶的輸入文本,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • Python實現(xiàn)替換文件中指定內(nèi)容的方法

    Python實現(xiàn)替換文件中指定內(nèi)容的方法

    這篇文章主要介紹了Python實現(xiàn)替換文件中指定內(nèi)容的方法,涉及Python文件讀寫、字符串替換等相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • Python中函數(shù)的基本定義與調(diào)用及內(nèi)置函數(shù)詳解

    Python中函數(shù)的基本定義與調(diào)用及內(nèi)置函數(shù)詳解

    這篇文章主要給大家介紹了關(guān)于Python中函數(shù)的基本定義與調(diào)用及內(nèi)置函數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Python list與NumPy array 區(qū)分詳解

    Python list與NumPy array 區(qū)分詳解

    這篇文章主要介紹了Python list與NumPy array 區(qū)分詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11

最新評論