Too strong, use Python+Excel to make a weather forecast table!

Hello everyone, I'm Xiao F~

Today I will introduce you a practical project of Python+Excel, which is very interesting.

Mainly use the two Python libraries xlwings and requests, as well as Office's Excel.

xlwings handles the form, requests is the request data.

First get the city information from Excel, then request the interface, get the weather information, and then return it to Excel.

The specific operation can be seen in the following figure~

Enter Hangzhou in the city column, click the query button, the data in the table will change, and it is indeed the weather forecast for Hangzhou.

① Data acquisition

Since it is a weather forecast, it definitely needs weather data.

I found a circle of domestic open weather API interfaces, most of which require registration, Xiao F decisively gave up.

Tencent has a good one, but unfortunately the interface information is not complete and there is no corresponding data explanation.

Address: https://tianqi.qq.com/

Interface address: https://wis.qq.com/weather/common

Finally, a foreign weather API interface was selected.

Address: https://www.metaweather.com/zh/

Not all cities in the country are provided, currently there are only 10 cities.

So if you want more cities, Tencent's weather interface can still be considered.

There are a total of 10 weather states, and related weather state pictures are provided for us to use.

The picture has been downloaded, and the friends who need it can get it at the end of the article!

First, get the ID value of the city by querying.

Then according to the ID value, go to get the corresponding weather information.

The Chinese and English versions of the relevant names are as follows.

# 天气--中英文名对照
weather = {
    'Snow': '雪',
    'Sleet': '雨夹雪',
    'Hail': '冰雹',
    'Thunderstorm': '雷阵雨',
    'Heavy Rain': '大雨',
    'Light Rain': '小雨',
    'Showers': '阵雨',
    'Heavy Cloud': '阴',
    'Light Cloud': '多云',
    'Clear': '晴'
}

# 城市--中英文名对照
citys = {
    '北京': 'Beijing',
    '成都': 'Chengdu',
    '东莞': 'Dongguan',
    '广州': 'Guangzhou',
    '杭州': 'Hangzhou',
    '香港': 'Hong Kong',
    '上海': 'Shanghai',
    '深圳': 'Shenzhen',
    '天津': 'Tianjin',
    '武汉': 'Wuhan'
}

② Create a form

Install the xlwings library and use the command line to create the project.

# 安装xlwings
pip install xlwings -i https://mirror.baidu.com/pypi/simple/

# 命令行运行
xlwings quickstart weatherapp --standalone

This will generate two files, a Python and an Excel file.

The content of the weatherapp.py file is as follows.

import xlwings as xw


def main():
    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    if sheet["A1"].value == "Hello xlwings!":
        sheet["A1"].value = "Bye xlwings!"
    else:
        sheet["A1"].value = "Hello xlwings!"


if __name__ == "__main__":
    xw.Book("weatherapp.xlsm").set_mock_caller()
    main()

And Excel is nothing, when you open it, you will be prompted whether to enable macros, select Yes .

Then you need to open the Excel development tool, which will be used to insert some elements later.

The picture above shows the settings of a Mac computer, and it is also very simple to set up a Windows computer, specifically Baidu.

By clicking on the Development Tools option, we can use the Visual Basic Editor (VBA) of Excle and insert buttons (query buttons).

Then I insert a click button in the form.

Select the macro name as SampleCall and the location of the macro as the current workbook.

Click button 1, the content Hello xlwings appears in cell A1! .

Click again, the content of cell A1 becomes Bye xlwings! .

That is to say, by modifying the code of the weatherapp.py file, you can realize the interactive operation of Excel.

The following is the page design of the table, after all, to make the table look good.

Set the row height, column width, background color, fixed text content and other information of the table.

Set the name of cell C3 to city_name, insert 6 pictures of the sun, arrange them in cells C9~H9, align them in the center, and rename the pictures to no.1~no.6.

Modify the weatherapp.py file code as follows.

import json
from pathlib import Path
import requests
import xlwings as xw

# 天气--中英文名对照
weather = {
    'Snow': '雪',
    'Sleet': '雨夹雪',
    'Hail': '冰雹',
    'Thunderstorm': '雷阵雨',
    'Heavy Rain': '大雨',
    'Light Rain': '小雨',
    'Showers': '阵雨',
    'Heavy Cloud': '阴',
    'Light Cloud': '多云',
    'Clear': '晴'
}

# 城市--中英文名对照
citys = {
    '北京': 'Beijing',
    '成都': 'Chengdu',
    '东莞': 'Dongguan',
    '广州': 'Guangzhou',
    '杭州': 'Hangzhou',
    '香港': 'Hong Kong',
    '上海': 'Shanghai',
    '深圳': 'Shenzhen',
    '天津': 'Tianjin',
    '武汉': 'Wuhan'
}


def main():
    # 通过runpython从excel中调用python函数
    wb = xw.Book.caller()
    sht = wb.sheets[0]

    # 从Excel中读取城市信息
    city_name = citys[sht.range("city_name").value]

    # 获取城市的ID值, 即woeid
    URL_CITY = f"https://www.metaweather.com/api/location/search/?query={city_name}"
    response_city = requests.request("GET", URL_CITY)
    city_title = json.loads(response_city.text)[0]["title"]
    city_id = json.loads(response_city.text)[0]["woeid"]

    # 获取城市的天气信息
    URL_WEATHER = f"https://www.metaweather.com/api/location/{city_id}/"
    response_weather = requests.request("GET", URL_WEATHER)
    weather_data = json.loads(response_weather.text)["consolidated_weather"]

    # 创建空列表, 存储数据
    min_temp = []
    max_temp = []
    weather_state_name = []
    weather_state_abbr = []
    applicable_date = []

    # 处理数据
    for index, day in enumerate(weather_data):
        # 最低温度
        min_temp.append(weather_data[index]["min_temp"])
        # 最高温度
        max_temp.append(weather_data[index]["max_temp"])
        # 天气情况
        weather_state_name.append(weather[weather_data[index]["weather_state_name"]])
        # 天气情况缩写
        weather_state_abbr.append(weather_data[index]["weather_state_abbr"])
        # 日期
        applicable_date.append(weather_data[index]["applicable_date"])

    # 将获取到的值填充到Excel中
    sht.range("C5").value = applicable_date
    sht.range("C6").value = weather_state_name
    sht.range("C7").value = max_temp
    sht.range("C8").value = min_temp
    sht.range("D3").value = city_title

    # 创建列表
    icon_names = ["no.1", "no.2", "no.3", "no.4", "no.5", "no.6"]

    # 设置天气图片路径
    icon_path = Path(__file__).parent / "images"

    # 将天气情况与天气图片进行匹配,更新表格
    for icon, abbr in zip(icon_names, weather_state_abbr):
        image_path = Path(icon_path, abbr + ".png")
        sht.pictures.add(image_path, name=icon, update=True)


if __name__ == "__main__":
    # 设置用于调试caller()的excel文件,可以直接在python里运行
    xw.Book("weatherapp.xlsm").set_mock_caller()
    main()

At this point, we open the Excel sheet, enter one of the 10 cities in the city column, and then click the query button, and the weather will be updated.

In the next few days, there will be heavy rainstorms in Guangzhou, and friends in Guangzhou should pay attention~

Well, the sharing of this issue is over, and interested friends can practice and learn by themselves.

Reply to " forecast " on the official account, you can get the code and data used this time.

  end book  

This time, Xiao F and [Peking University Press] bring you 5 books related to algorithms.

" Python Optimization Algorithm in Practice " uses Python as a development language to explain the principles and applications of optimization algorithms. Detailed introduction to Python basics, Gurobi optimizer, linear programming, integer programming, multi-objective optimization, dynamic programming, graph and network analysis, and intelligent optimization algorithms. Click the image below to see details/purchase????

Book donation rules : After you like this article ("I'm watching" is not required), scan the QR code below and add Xiao F's WeChat. Send me the screenshots of the likes, and I will send the lucky draw code to everyone. The deadline is 21:00 on May 31.

Thank you all for your support of F!

Recommended reading

···  END  ···

Guess you like

Origin blog.csdn.net/river_star1/article/details/117408552