首页 > Python资料 博客日记

python爬虫——爬取全年天气数据并做可视化分析

2024-09-21 17:00:05Python资料围观4

Python资料网推荐python爬虫——爬取全年天气数据并做可视化分析这篇文章给大家,欢迎收藏Python资料网享受知识的乐趣

一、主题页面的结构与特征分析

1.主题页面的结构与特征分析

目标内容界面:

2. Htmls 页面解析

3.节点查找方法与遍历方法

查找方法:find(): 查找第一个匹配到的节点。find_all(): 查找所有匹配到的节点,并返回一个列表。

遍历方法:contents: 返回当前节点的直接子节点列表。 children: 返回当前节点的直接子节点的迭代器。descendants: 返回当前节点的所有子孙节点的迭代器。

parent: 返回当前节点的父节点。parents: 返回当前节点的所有祖先节点的迭代器。

二、网络爬虫程序设计

1.数据爬取与采集

数据源:https://lishi.tianqi.com/quanzhou/

所用到的库有

1 import requests # 模拟浏览器进行网络请求
2 from lxml import etree # 进行数据预处理
3 import csv # 进行写入csv文件

使用requests中的get方法对网站发出请求,并接收响应数据,

1 resp = requests.get(url, headers=headers)

我们便得到了网页的源代码数据,

2.对数据进行清洗和处理

然后对爬取的网站源代码进行预处理

1 resp_html = etree.HTML(resp.text)

使用xpath工具提取我们所需要的数据

1 resp_list = resp_html.xpath(“//ul[@class=‘thrui’]/li”)

创建一个字典,并使用for循环将我们所提取的数据,放入字典中

 1 for li in resp\_list: 2 day\_weather\_info = {} 3 # 日期
 4 day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]
 5 # 最高气温 (包含摄氏度符号)
 6 high = li.xpath("./div\[2\]/text()")\[0\]
 7 day\_weather\_info\['high'\] = high\[:high.find('℃')\]
 8 # 最低气温
 9 low = li.xpath("./div\[3\]/text()")\[0\]
10 day\_weather\_info\['low'\] = low\[:low.find('℃')\]
11 # 天气
12 day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]
13 weather\_info.append(day\_weather\_info)
14 return weather\_info

然后我们便得到了我们所需要的数据

接着爬取我们这个月的天气信息,存入列表中,然一次性写入我们的csv文件中,这样我们就得到了一个存有泉州2022全年天气情况的文件

# for循环生成有顺序的1-12
for month in range(1, 13):
    # 获取某一月的天气信息
    # 三元表达式
    weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
    print(weather\_time)
    url \= f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
    # 爬虫获取这个月的天气信息
    weather = getWeather(url)
    # 存到列表中
    weathers.append(weather)
print(weathers)

# 数据写入(一次性写入)
with open("weather.csv", "w",newline='') as csvfile:
    writer \= csv.writer(csvfile)
    # 先写入列名:columns\_name 日期 最高气温 最低气温  天气
    writer.writerow(\["日期", "最高气温", "最低气温", '天气'\])
    # 一次写入多行用writerows(写入的数据类型是列表,一个列表对应一行)
    writer.writerows(\[list(day\_weather\_dict.values()) for month\_weather in weathers for day\_weather\_dict in month\_weather\])
import sqlite3

文件如下:

3.对我们的数据进行一下词云处理

所用到的库

1 import requests
2 from lxml import etree
3 import csv
4 from wordcloud import WordCloud
5 import matplotlib.pyplot as plt

然后对数据在进行一次爬取与清理

 1 # 从URL获取天气信息的函数
 2 def getWeather(url): 3     weather\_info = \[\]  # 存储天气信息的列表
 4     headers = { 5         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
 6     }
 7     resp = requests.get(url, headers=headers)  # 发送GET请求到指定的URL
 8     resp\_html = etree.HTML(resp.text)  # 解析响应的HTML
 9     resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li")  # 使用XPath选择器提取天气信息列表
10     for li in resp\_list:
11         day\_weather\_info = {}  # 存储每天天气信息的字典
12         day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]  # 提取日期时间并存入字典
13         high = li.xpath("./div\[2\]/text()")\[0\]  # 提取最高温度
14         day\_weather\_info\['high'\] = high\[:high.find('℃')\]  # 去除温度单位并存入字典
15         low = li.xpath("./div\[3\]/text()")\[0\]  # 提取最低温度
16         day\_weather\_info\['low'\] = low\[:low.find('℃')\]  # 去除温度单位并存入字典
17         day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]  # 提取天气情况并存入字典
18         weather\_info.append(day\_weather\_info)  # 将每天天气信息字典添加到天气信息列表中
19     return weather\_info
20 def main():
21     weathers = \[\]  # 存储所有月份的天气信息的列表
22     for month in range(1, 13):
23         weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
24         print(weather\_time)
25         url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
26         weather = getWeather(url)
27         weathers.append(weather)  # 将每个月份的天气信息添加到weathers列表中
28     print(weathers)
29 
30     weather\_data = ""  # 存储所有天气情况的字符串
31     for month\_weather in weathers:
32         for day\_weather\_dict in month\_weather:
33             weather = day\_weather\_dict\['weather'\]  # 提取天气情况
34             weather\_data += weather + " "  # 将天气情况添加到weather\_data字符串中,用空格分隔

然后便得到了我们熟悉的数据

wordcloud的分词可视化处理

1    wordcloud = WordCloud(font\_path='C:\\Windows\\Fonts\\微软雅黑\\msyh.ttc', width=800, height=400, font\_step=1,
2                           prefer\_horizontal=0.9).generate(weather\_data)  # 根据天气数据生成词云
3     plt.figure(figsize=(10, 5))
4     plt.imshow(wordcloud, interpolation='bilinear')  # 显示词云图像
5     plt.axis('off')
6 plt.show()
7 
8 if \_\_name\_\_ == '\_\_main\_\_':
9     main()

4.数据持久化

import sqlite3

def create\_weather\_table():
    conn \= sqlite3.connect('weather.db')  # 连接到数据库文件
    cursor = conn.cursor()

    # 创建天气表格
    cursor.execute('''CREATE TABLE IF NOT EXISTS weather (
                        date\_time TEXT,
                        high TEXT,
                        low TEXT,
                        weather TEXT
                    )''')  # 创建天气表格,如果不存在则创建
    conn.commit()  # 提交更改到数据库
    conn.close()  # 关闭数据库连接

def insert\_weather\_data(weather\_data):
    conn \= sqlite3.connect('weather.db')  # 连接到数据库文件
    cursor = conn.cursor()

    # 插入天气数据
    for month\_weather in weather\_data:
        for day\_weather\_dict in month\_weather:
            date\_time \= day\_weather\_dict\['date\_time'\]  # 获取日期时间
            high = day\_weather\_dict\['high'\]  # 获取最高温度
            low = day\_weather\_dict\['low'\]  # 获取最低温度
            weather = day\_weather\_dict\['weather'\]  # 获取天气情况
            cursor.execute("INSERT INTO weather VALUES (?, ?, ?, ?)", (date\_time, high, low, weather))  # 插入数据到天气表格
    conn.commit()  # 提交更改到数据库
    conn.close()  # 关闭数据库连接

def main():
    create\_weather\_table()  # 创建天气表格
    weathers \= \[\]  # 存储所有月份的天气信息的列表
    for month in range(1, 13):
        weather\_time \= '2022' + ('0' + str(month) if month < 10 else str(month))
        print(weather\_time)
        url \= f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
        weather \= getWeather(url)  # 获取天气信息

weathers.append(weather)
print(weathers)

insert\_weather\_data(weathers)

if \_\_name\_\_ == '\_\_main\_\_':
    main()

然后数据便以库文件的方式存入电脑中

5.数据可视化

所用到的库

1 import pandas as pd
2 from pyecharts import options as opts
3 from pyecharts.charts import Pie, Bar, Timeline, Line, Scatter

使用pandas.read_csv()读取我们数据文件

1 df = pd.read_csv(‘weather.csv’,encoding=‘gb18030’)

因为绘制的图形是动态的天气轮播图,而此时我们日期的数据类型为字符串,要将类型改为datetime

1 df[‘日期’] = df[‘日期’].apply(lambda x: pd.to_datetime(x))

使用GroupBy聚合对象 以及size().reset_index()方法来将每种天气出现的次数等数据进行分组,统计。

1 df\_agg = df.groupby(\['month','天气'\]).size().reset\_index()
2 print(df\_agg)

对每列数据进行一个命名

df\_agg.columns = \['month','tianqi','count'\]
print(df\_agg)

将数据转化为列表数据

1 print(df\_agg\[df\_agg\['month'\]==1\]\[\['tianqi','count'\]\]\\
2     .sort\_values(by='count',ascending=False).values.tolist())

将处理好的数据传入图表中,绘制横放柱状轮播图

 1 # 画图
 2 # 实例化一个时间序列的对象
 3 timeline = Timeline() 4 # 播放参数:设置时间间隔 1s  单位是:ms(毫秒)
 5 timeline.add\_schema(play\_interval=1000)    # 单位是:ms(毫秒)
 6 
 7 # 循环遍历df\_agg\['month'\]里的唯一值
 8 for month in df\_agg\['month'\].unique():
 9     data = (
10 
11         df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
12         .sort\_values(by='count',ascending=True)
13 .values.tolist()
14 )
15     # print(data)
16     # 绘制柱状图
17     bar = Bar()
18     # x轴是天气名称
19     bar.add\_xaxis(\[x\[0\] for x in data\])
20     # y轴是出现次数
21     bar.add\_yaxis('',\[x\[1\] for x in data\])
22 
23     # 让柱状图横着放
24 bar.reversal\_axis()
25     # 将计数标签放置在图形右边
26     bar.set\_series\_opts(label\_opts=opts.LabelOpts(position='right'))
27     # 设置下图表的名称
28     bar.set\_global\_opts(title\_opts=opts.TitleOpts(title='泉州2022年每月天气变化 '))
29     # 将设置好的bar对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
30     timeline.add(bar, f'{month}月')
31 
32 # 将设置好的图表保存为'weathers.html'文件
33 timeline.render('weathers1.html')

#由于视频上传不了,所以只放了两个月份的天气数据图片

绘制折线图

 1 # 画图
 2 # 实例化一个时间序列的对象
 3 timeline = Timeline() 4 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
 5 timeline.add\_schema(play\_interval=1000)  # 单位是:ms(毫秒)
 6 
 7 # 循环遍历df\_agg\['tianqi'\]里的唯一值(天气类型)
 8 for tianqi in df\_agg\['tianqi'\].unique():
 9     data = (
10         df\_agg\[df\_agg\['tianqi'\] == tianqi\]\[\['month', 'count'\]\]
11         .sort\_values(by='month', ascending=True)
12 .values.tolist()
13 )
14     # print(data)
15     # 绘制折线图
16     line = Line()
17     # x轴是月份
18     line.add\_xaxis(\[x\[0\] for x in data\])
19     # y轴是出现次数
20     line.add\_yaxis(tianqi, \[x\[1\] for x in data\], is\_smooth=True)
21 
22     # 设置图线平滑曲线
23 line.set\_series\_opts(
24         markpoint\_opts=opts.MarkPointOpts(
25             data=\[opts.MarkPointItem(type\_="max", name="最大值")\]
26 )
27 )
28 
29     # 设置下图表的名称
30 line.set\_global\_opts(
31         title\_opts=opts.TitleOpts(title='泉州2022年天气趋势'),
32         datazoom\_opts=opts.DataZoomOpts(type\_="slider", range\_start=0, range\_end=100),
33 )
34 
35     # 将设置好的line对象放置到时间轮播图中,并且标签选择天气类型
36 timeline.add(line, tianqi)
37 
38 # 将设置好的时间轮播图渲染为HTML文件
39 timeline.render("weather\_trend.html")

绘制散点图

 1 # 画图
 2 # 实例化一个散点图对象
 3 scatter = Scatter() 4 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
 5 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
 6 
 7 # 循环遍历df\_agg\['month'\]里的唯一值
 8 for month in df\_agg\['month'\].unique():
 9     data = (
10         df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
11         .sort\_values(by='count',ascending=True)
12 .values.tolist()
13 )
14     # 绘制散点图
15     scatter = Scatter()
16     # x轴是天气名称
17     scatter.add\_xaxis(\[x\[0\] for x in data\])
18     # y轴是出现次数
19     scatter.add\_yaxis('',\[x\[1\] for x in data\])
20 
21     # 设置下图表的名称
22     scatter.set\_global\_opts(title\_opts=opts.TitleOpts(title=f'{month}月天气散点图'))
23 
24     # 将设置好的scatter对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
25     timeline.add(scatter, f'{month}月')
26 
27 # 将设置好的时间轮播图渲染为html文件
28 timeline.render('scatter\_timeline.html')

根据以上几个可视化图形可知

泉州市的降雨集中在5月至9月期间,而晴天比较多的月份是10月至来年3月。

6.将以上各部分的代码汇总,附上完整程序代码

(1)数据爬取与清洗,以及持久化部分

  1 #\-\*- coding: utf-8 -\*-
  2 import requests  # 模拟浏览器进行网络请求
  3 from lxml import etree  # 进行数据预处理
  4 import csv  # 写入csv文件
  5 import sqlite3  6 def getWeather(url):  7     weather\_info = \[\]   # 新建一个列表,将爬取的每月数据放进去
  8     # 请求头信息:浏览器版本型号,接收数据的编码格式
  9     headers = { 10         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
 11     }
 12     # 请求 接收到了响应数据
 13     resp = requests.get(url, headers=headers)
 14     # 数据预处理s
 15     resp\_html = etree.HTML(resp.text) 16     # xpath提取所有数据
 17     resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li")
 18     # for循环迭代遍历
 19     for li in resp\_list: 20         day\_weather\_info = {} 21         # 日期
 22         day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]
 23         # 最高气温 (包含摄氏度符号)
 24         high = li.xpath("./div\[2\]/text()")\[0\]
 25         day\_weather\_info\['high'\] = high\[:high.find('℃')\]
 26         # 最低气温
 27         low = li.xpath("./div\[3\]/text()")\[0\]
 28         day\_weather\_info\['low'\] = low\[:low.find('℃')\]
 29         # 天气
 30         day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]
 31         weather\_info.append(day\_weather\_info)
 32     return weather\_info 33 
 34 weathers = \[\] 35 
 36 # for循环生成有顺序的1-12
 37 for month in range(1, 13):
 38     # 获取某一月的天气信息
 39     # 三元表达式
 40     weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month)) 41     print(weather\_time)
 42     url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
 43     # 爬虫获取这个月的天气信息
 44     weather = getWeather(url) 45     # 存到列表中
 46     weathers.append(weather)
 47 print(weathers)
 48 
 49 
 50 # 数据写入(一次性写入)
 51 with open("weather.csv", "w",newline='') as csvfile:
 52     writer = csv.writer(csvfile) 53     # 先写入列名:columns\_name 日期 最高气温 最低气温  天气
 54     writer.writerow(\["日期", "最高气温", "最低气温", '天气'\])
 55     # 一次写入多行用writerows(写入的数据类型是列表,一个列表对应一行)
 56     writer.writerows(\[list(day\_weather\_dict.values()) for month\_weather in weathers for day\_weather\_dict in month\_weather\]) 57 
 58 
 59 import sqlite3 60 
 61 
 62 def create\_weather\_table(): 63     conn = sqlite3.connect('weather.db')  # 连接到数据库文件
 64     cursor = conn.cursor() 65 
 66     # 创建天气表格
 67     cursor.execute('''CREATE TABLE IF NOT EXISTS weather (
 68                         date\_time TEXT,
 69                         high TEXT,
 70                         low TEXT,
 71                         weather TEXT
 72                     )''')  # 创建天气表格,如果不存在则创建
 73 
 74     conn.commit()  # 提交更改到数据库
 75     conn.close()  # 关闭数据库连接
 76 
 77 
 78 def insert\_weather\_data(weather\_data): 79     conn = sqlite3.connect('weather.db')  # 连接到数据库文件
 80     cursor = conn.cursor() 81 
 82     # 插入天气数据
 83     for month\_weather in weather\_data: 84         for day\_weather\_dict in month\_weather: 85             date\_time = day\_weather\_dict\['date\_time'\]  # 获取日期时间
 86             high = day\_weather\_dict\['high'\]  # 获取最高温度
 87             low = day\_weather\_dict\['low'\]  # 获取最低温度
 88             weather = day\_weather\_dict\['weather'\]  # 获取天气情况
 89 
 90             cursor.execute("INSERT INTO weather VALUES (?, ?, ?, ?)", (date\_time, high, low, weather))  # 插入数据到天气表格
 91 
 92     conn.commit()  # 提交更改到数据库
 93     conn.close()  # 关闭数据库连接
 94 
 95 
 96 def main(): 97     create\_weather\_table()  # 创建天气表格
 98 
 99     weathers = \[\]  # 存储所有月份的天气信息的列表
100     for month in range(1, 13):
101         weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
102         print(weather\_time)
103         url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
104         weather = getWeather(url)  # 获取天气信息
105 
106 
107 weathers.append(weather)
108 print(weathers)
109 
110 insert\_weather\_data(weathers)
111 
112 if \_\_name\_\_ == '\_\_main\_\_':
113     main()

(2)数据可视化部分

  1 #\-\*- coding: utf-8 -\*-
  2 
  3 # 数据分析 读取 处理 存储
  4 import pandas as pd  5 from pyecharts import options as opts  6 from pyecharts.charts import Pie, Bar, Timeline, Line, Scatter  7 
  8 # 用pandas.read\_csv()读取指定的excel文件,选择编码格式gb18030(gb18030范围比)
  9 df = pd.read\_csv('weather.csv',encoding='gb18030')
 10 print(df\['日期'\])
 11 
 12 # 将日期格式的数据类型改为month
 13 df\['日期'\] = df\['日期'\].apply(lambda x: pd.to\_datetime(x)) 14 print(df\['日期'\])
 15 
 16 
 17 # 新建一列月份数据(将日期中的月份month 一项单独拿取出来)
 18 df\['month'\] = df\['日期'\].dt.month
 19 
 20 print(df\['month'\])
 21 # 需要的数据 每个月中每种天气出现的次数
 22 
 23 # DataFrame GroupBy聚合对象 分组和统计的  size()能够计算分组的大小
 24 df\_agg = df.groupby(\['month','天气'\]).size().reset\_index()
 25 print(df\_agg)
 26 
 27 # 设置下这3列的列名
 28 df\_agg.columns = \['month','tianqi','count'\]
 29 print(df\_agg)
 30 
 31 # 转化为列表数据
 32 print(df\_agg\[df\_agg\['month'\]==1\]\[\['tianqi','count'\]\]\\
 33     .sort\_values(by='count',ascending=False).values.tolist())
 34 """
 35 \[\['阴', 20\], \['多云', 5\], \['雨夹雪', 4\], \['晴', 2\]\]
 36 """
 37 
 38 # 画图
 39 # 实例化一个时间序列的对象
 40 timeline = Timeline() 41 # 播放参数:设置时间间隔 1s  单位是:ms(毫秒)
 42 timeline.add\_schema(play\_interval=1000)    # 单位是:ms(毫秒)
 43 
 44 # 循环遍历df\_agg\['month'\]里的唯一值
 45 for month in df\_agg\['month'\].unique():
 46     data = ( 47 
 48         df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
 49         .sort\_values(by='count',ascending=True)
 50         .values.tolist()
 51     )
 52     # print(data)
 53     # 绘制柱状图
 54     bar = Bar() 55     # x轴是天气名称
 56     bar.add\_xaxis(\[x\[0\] for x in data\]) 57     # y轴是出现次数
 58     bar.add\_yaxis('',\[x\[1\] for x in data\]) 59 
 60     # 让柱状图横着放
 61     bar.reversal\_axis()
 62     # 将计数标签放置在图形右边
 63     bar.set\_series\_opts(label\_opts=opts.LabelOpts(position='right'))
 64     # 设置下图表的名称
 65     bar.set\_global\_opts(title\_opts=opts.TitleOpts(title='泉州2022年每月天气变化 '))
 66     # 将设置好的bar对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
 67     timeline.add(bar, f'{month}月')
 68 
 69 # 将设置好的图表保存为'weathers.html'文件
 70 timeline.render('weathers1.html')
 71 
 72 
 73 # 画图
 74 # 实例化一个时间序列的对象
 75 timeline = Timeline() 76 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
 77 timeline.add\_schema(play\_interval=1000)  # 单位是:ms(毫秒)
 78 
 79 # 循环遍历df\_agg\['tianqi'\]里的唯一值(天气类型)
 80 for tianqi in df\_agg\['tianqi'\].unique():
 81     data = ( 82         df\_agg\[df\_agg\['tianqi'\] == tianqi\]\[\['month', 'count'\]\]
 83         .sort\_values(by='month', ascending=True)
 84         .values.tolist()
 85     )
 86     # print(data)
 87     # 绘制折线图
 88     line = Line() 89     # x轴是月份
 90     line.add\_xaxis(\[x\[0\] for x in data\]) 91     # y轴是出现次数
 92     line.add\_yaxis(tianqi, \[x\[1\] for x in data\], is\_smooth=True)
 93 
 94     # 设置图线平滑曲线
 95     line.set\_series\_opts(
 96         markpoint\_opts=opts.MarkPointOpts(
 97             data=\[opts.MarkPointItem(type\_="max", name="最大值")\]
 98         )
 99 )
100 
101     # 设置下图表的名称
102 line.set\_global\_opts(
103         title\_opts=opts.TitleOpts(title='泉州2022年天气趋势'),
104         datazoom\_opts=opts.DataZoomOpts(type\_="slider", range\_start=0, range\_end=100),
105 )
106 
107     # 将设置好的line对象放置到时间轮播图中,并且标签选择天气类型
108 timeline.add(line, tianqi)
109 
110 # 将设置好的时间轮播图渲染为HTML文件
111 timeline.render("weather\_trend.html")
112 
113 # 画图
114 # 实例化一个散点图对象
115 scatter = Scatter()
116 # 播放参数:设置时间间隔 1s 单位是:ms(毫秒)
117 timeline.add\_schema(play\_interval=1000) # 单位是:ms(毫秒)
118 
119 # 循环遍历df\_agg\['month'\]里的唯一值
120 for month in df\_agg\['month'\].unique():
121     data = (
122         df\_agg\[df\_agg\['month'\]==month\]\[\['tianqi','count'\]\]
123         .sort\_values(by='count',ascending=True)
124 .values.tolist()
125 )
126     # 绘制散点图
127     scatter = Scatter()
128     # x轴是天气名称
129     scatter.add\_xaxis(\[x\[0\] for x in data\])
130     # y轴是出现次数
131     scatter.add\_yaxis('',\[x\[1\] for x in data\])
132 
133     # 设置下图表的名称
134     scatter.set\_global\_opts(title\_opts=opts.TitleOpts(title=f'{month}月天气散点图'))
135 
136     # 将设置好的scatter对象放置到时间轮播图当中,并且标签选择月份 格式为: 数字月
137     timeline.add(scatter, f'{month}月')
138 
139 # 将设置好的时间轮播图渲染为html文件
140 timeline.render('scatter\_timeline.html')
141 import numpy as np
142 from sklearn.linear\_model import LinearRegression

(3)wordcloud分词可视化,词云部分

 1  1 # -\*- coding: utf-8 -\*-
 2  2 
 3  3 # 导入必要的库
 4  4 import requests 5  5 from lxml import etree 6  6 import csv 7  7 from wordcloud import WordCloud 8  8 import matplotlib.pyplot as plt 9  9 
10 10 # 从URL获取天气信息的函数s
11 11 def getWeather(url):
12 12     weather\_info = \[\]  # 存储天气信息的列表
13 13     headers = {
14 14         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
15 15     }
16 16     resp = requests.get(url, headers=headers)  # 发送GET请求到指定的URL
17 17     resp\_html = etree.HTML(resp.text)  # 解析响应的HTML
18 18     resp\_list = resp\_html.xpath("//ul\[@class='thrui'\]/li")  # 使用XPath选择器提取天气信息列表
19 19     for li in resp\_list:
20 20         day\_weather\_info = {}  # 存储每天天气信息的字典
21 21         day\_weather\_info\['date\_time'\] = li.xpath("./div\[1\]/text()")\[0\].split(' ')\[0\]  # 提取日期时间并存入字典
22 22         high = li.xpath("./div\[2\]/text()")\[0\]  # 提取最高温度
23 23         day\_weather\_info\['high'\] = high\[:high.find('℃')\]  # 去除温度单位并存入字典
24 24         low = li.xpath("./div\[3\]/text()")\[0\]  # 提取最低温度
25 25         day\_weather\_info\['low'\] = low\[:low.find('℃')\]  # 去除温度单位并存入字典
26 26         day\_weather\_info\['weather'\] = li.xpath("./div\[4\]/text()")\[0\]  # 提取天气情况并存入字典
27 27         weather\_info.append(day\_weather\_info)  # 将每天天气信息字典添加到天气信息列表中
28 28     return weather\_info
29 29 def main():
30 30     weathers = \[\]  # 存储所有月份的天气信息的列表
31 31     for month in range(1, 13):
32 32         weather\_time = '2022' + ('0' + str(month) if month < 10 else str(month))
33 33         print(weather\_time)
34 34         url = f'https://lishi.tianqi.com/quanzhou/{weather\_time}.html'
35 35         weather = getWeather(url)
36 36         weathers.append(weather)  # 将每个月份的天气信息添加到weathers列表中
37 37     print(weathers)
38 38 
39 39     weather\_data = ""  # 存储所有天气情况的字符串
40 40     for month\_weather in weathers:
41 41         for day\_weather\_dict in month\_weather:
42 42             weather = day\_weather\_dict\['weather'\]  # 提取天气情况
43 43             weather\_data += weather + " "  # 将天气情况添加到weather\_data字符串中,用空格分隔
44 44 
45 45     wordcloud = WordCloud(font\_path='C:\\Windows\\Fonts\\微软雅黑\\msyh.ttc', width=800, height=400, font\_step=1,
46 46                           prefer\_horizontal=0.9).generate(weather\_data)  # 根据天气数据生成词云
47 47     plt.figure(figsize=(10, 5))
48 48     plt.imshow(wordcloud, interpolation='bilinear')  # 显示词云图像
49 49     plt.axis('off')
50 50     plt.show()
51 51 
52 52 if \_\_name\_\_ == '\_\_main\_\_':
53 53     main()


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐