Python Makes Weather Query Software

Insert a picture description here

Previously, Public Number shared how to use PyQt5 to make guess games and timers. This time, let's continue to learn how to use PyQt5 to make weather query software.
For source code and exe files, please reply in the Wechat Public Number Python Efficient Programming Background: Weather.
PS Note: Many people will encounter various troubles when learning Python, and no one can easily give up without an answer.A free Python answer stack has been created for this little one. Skirt: seven clothes, ninety-seven bars and five (digital homophonic) can be found under the conversion, old drivers can solve problems they do not understand, there is also the latest Python actual combat tutorial, so we can monitor each other and make progress together!

development environment

  • Python3
  • PyQt5
  • requests

Dead work

First, get the weather codes for the different cities from https://www.heweather.com/documents/city.html The website downloads the csv file (get the csv file at the end of the article) and gets the csv file, so we have to do data preprocessing first.

import pandas as pd
# Name the downloaded file'city_code.csv'and delete the header
file = pd.read_csv('city_code.csv')
# Select the two columns of information you want
file = file.loc[:,['City_ID', 'City_CN']]
# Read the first five lines of information
file.head()
 
Insert a picture description here
# Match numbers in City_ID
def convert(x):
    pat = re.compile('(\d+)')
    return pat.search(x).group()

file['City_ID_map'] = file['City_ID'].map(convert)

# Establish a mapping relationship between cities and codes
def city2id(file):
    code_dict = {}
    key = 'City_CN'
    value = 'City_ID_map'
    for k, v in zip(file[key], file[value]):
        code_dict[k] = v
    return code_dict
code_dict = city2id(file)

# Store all dictionary data as a txt file
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
    json.dump(code_dict, f)

After storing the dictionary as a txt file, we only need to read the file later to get the dictionary:

with open(filename, 'r') as f:
    text = json.load(f)

If you don't want to work on the data, you can use the city_code.txt file provided at the end.

Ui Design

With Qt Designer, it is not difficult to design the following interfaces:

 
Insert a picture description here

 

If you don't want to design these interfaces, you can import the Ui_weather.py file I provided directly.

Subject logic:

The api interface we are using this time is: ' http://wthrcdn.etouch.cn/weather_mini?citykey= {code}', code is the city code that was previously processed, such as Changzhou city code: 101191101.Replace the variable code and the website returns us a json-formatted file:

 
Insert a picture description here

From this json statement, we can easily extract the information we need:

# weather condition
data = info_json['data']
city = f"City:{data['city']}\n"
today = data['forecast'][0]
date = f"Date:{today['date']}\n"
now = f"Real-time temperature:{data['wendu']}degree\n"
temperature = f"Temperature:{today['high']} {today['low']}\n"
fengxiang = f"Wind direction:{today['fengxiang']}\n"
type = f"Weather:{today['type']}\n"
tips = f"Tips:{data['ganmao']}\n"

Of course, the first step is to use the requests,get method to get this json code.

def query_weather(code):
    # Template Web Page
    html = f'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'
    
    # Initiate a request to a Web page
    try:
        info = requests.get(html)
        info.encoding = 'utf-8'
    # Catch ConnectinError Exception
    except requests.ConnectionError:
        raise 
    
    
    
    # Convert the acquired data to json format
    try:
        info_json = info.json()
    # Conversion failure prompt cannot be queried
    except JSONDecodeError:
        return 'Unable to query'

Here we describe the control methods used in this article:

# Set textEdit to read-only mode
self.textEdit.setReadOnly(True)
# Focus the mouse on the lineEdit edit bar
self.lineEdit.setFocus()
# Get text in lineEdit
city = self.lineEdit.text()
# Set Text
self.textEdit.setText(info)
# Empty Text
self.lineEdit.clear()

Set shortcuts for query buttons:

def keyPressEvent(self, e):
# Set Shortcut
    if e.key() == Qt.Key_Return:
        self.queryWeather()

Finally, we can use Pyinstaller -w weather.py to package the application, but remember to package it and copy city_code.txt to the dist/weather folder, otherwise the program will not run.

That's all for this article. See the source code for more details.If you need to get the source code and exe files, note: Many people will encounter various troubles when learning Python, and no one can easily give up the solution.A free Python answer stack has been created for this little one. Skirt: seven clothes, ninety-seven bars and five (digital homophonic) can be found under the conversion, old drivers can solve problems they do not understand, there is also the latest Python actual combat tutorial, so we can monitor each other and make progress together!

The text and pictures in this article come from the Internet plus your own ideas. They are for learning and communication purposes only. They do not have any commercial use. Copyright is owned by the original author. If you have any questions, please contact us in time for processing.

 
 

Tags: Python JSON Qt Programming

Posted on Thu, 19 Mar 2020 23:53:50 -0700 by zubinkasad