Python   发布时间:2022-04-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Python爬虫实战,pyecharts模块,Python实现中国地铁数据可视化大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

利用Python实现中国地铁数据可视化。废话不多说。

让我们愉快地开始吧~

开发工具

Python版本:3.6.4

相关模块:

requests模块;

wordcloud模块;

pandas模块;

numpy模块;

jieba模块;

pyecharts模块;

@H_525_24@matplotlib模块;

以及一些Python自带的模块。

环境搭建

很多人学习蟒蛇,不知道从何学起。

很多人学习寻找python,掌握了基本语法之后,不知道在哪里案例上手。

很多已经可能知道案例的人,却不怎么去学习更多高深的知识。

这三类人,我给大家提供一个好的学习平台,免费获取视频教程,电子书,以及课程的源代码!

QQ群:101677771

欢迎加入,一起讨论学习

 

安装Python并添加到环境变量,pip安装需要的相关模块即可。

本次通过对地铁线路数据的获取,对城市分布情况数据进行可视化分析。

分析获取

地铁信息获取从高德地图上获取。

上面主要获取城市的「id」,「cityname」及「名称」。

用于拼接请求网址,进而获取地铁线路的具体信息。

找到请求信息,获取各个城市的地铁线路以及线路中站点详情。

获取数据

具体代码

import json
import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}

def get_message(ID, cityname, Name):
    """
    地铁线路信息获取
    """
    url = 'http://map.amap.com/service/subway?_1555502190153&srhdata=' + ID + '_drw_' + cityname + '.json'
    response = requests.get(url=url, headers=headers)
    html = response.text
    result = json.loads(html)
    for i in result['l']:
        for j in I['st']:
            # 判断是否含有地铁分线
            if len(I['la']) > 0:
                print(name, I['ln'] + '(' + I['la'] + ')', j['n'])
                with open('subway.csv', 'a+', encoding='gbk') as f:
                    f.write(name + ',' + I['ln'] + '(' + I['la'] + ')' + ',' + j['n'] + '\n')
            else:
                print(name, I['ln'], j['n'])
                with open('subway.csv', 'a+', encoding='gbk') as f:
                    f.write(name + ',' + I['ln'] + ',' + j['n'] + '\n')

def get_city():
    """
    城市信息获取
    """
    url = 'http://map.amap.com/subway/index.html?&1100'
    response = requests.get(url=url, headers=headers)
    html = response.text
    # 编码
    html = html.encode('ISO-8859-1')
    html = html.decode('utf-8')
    soup = BeautifulSoup(html, 'lxml')
    # 城市列表
    res1 = soup.find_all(class_="city-list fl")[0]
    res2 = soup.find_all(class_="more-city-list")[0]
    for i in res1.find_all('a'):
        # 城市ID值
        ID = I['id']
        # 城市拼音名
        cityname = I['cityname']
        # 城市名
        name = i.get_text()
        get_message(ID, cityname, Name)
    for i in res2.find_all('a'):
        # 城市ID值
        ID = I['id']
        # 城市拼音名
        cityname = I['cityname']
        # 城市名
        name = i.get_text()
        get_message(ID, cityname, Name)

if __name__ == '__main__':
    get_city()

获取数据结果展示

3541个地铁站点

数据可视化

对数据进行清洗,去除重复的换乘站信息。

from wordcloud import WordCloud, ImageColorGenerator
from pyecharts import Line, Bar
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import jieba

# 设置列名与数据对齐
pd.set_option('display.unicode.ambiguous_as_wide', TruE)
pd.set_option('display.unicode.east_asian_width', TruE)
# 显示10行
pd.set_option('display.max_rows', 10)
# 读取数据
df = pd.read_csv('subway.csv', header=None, names=['city', 'line', 'station'], encoding='gbk')
# 各个城市地铁线路情况
df_line = df.groupby(['city', 'line']).count().reset_index()
print(df_linE)

通过城市及地铁线路进行分组,得到全国地铁线路总数。

183条地铁线路

def create_map(df):
    # 绘制地图
    value = [i for i in df['line']]
    attr = [i for i in df['city']]
    geo = Geo("已开通地铁城市分布情况", title_pos='center', title_top='0', width=800, height=400, title_color="#fff", BACkground_color="#404a59", )
    geo.add("", attr, value, is_visualmap=True, visual_range=[0, 25], visual_text_color="#fff", symbol_size=15)
    geo.render("已开通地铁城市分布情况.html")

def create_line(df):
    """
    生成城市地铁线路数量分布情况
    """
    title_len = df['line']
    bins = [0, 5, 10, 15, 20, 25]
    level = ['0-5', '5-10', '10-15', '15-20', '20以上']
    len_stage = pd.cut(title_len, bins=bins, labels=level).value_counts().sort_index()
    # 生成柱状图
    attr = len_stage.index
    v1 = len_stage.values
    bar = Bar("各城市地铁线路数量分布", title_pos='center', title_top='18', width=800, height=400)
    bar.add("", attr, v1, is_stack=True, is_label_show=TruE)
    bar.render("各城市地铁线路数量分布.html")

# 各个城市地铁线路数
df_city = df_line.groupby(['city']).count().reset_index().sort_values(by='line', ascending=falsE)
print(df_city)
create_map(df_city)
create_line(df_city)

已经开通地铁的城市数据,还有各个城市的地铁线路数。

32个城市开通地铁

城市分布情况

大部分都是省会城市,还有个别经济实力强的城市。

线路数量分布情况

可以看到大部分还是在「0-5」这个阶段的,当然最少为1条线。

# 哪个城市哪条线路地铁站最多
print(df_line.sort_values(by='station', ascending=falsE))

哪个城市哪条线路地铁站最多

@H_@R_673_11235@_132@北京10号线第一,重庆3号线第二

去除重复换乘站的数据

# 去除重复换乘站的地铁数据
df_station = df.groupby(['city', 'station']).count().reset_index()
print(df_station)

包含3034个地铁站

减少了近400个地铁站

接下来看一下哪个城市地铁站最多

# 统计每个城市包含地铁站数(已去除重复换乘站)
print(df_station.groupby(['city']).count().reset_index().sort_values(by='station', ascending=falsE))

武汉居然有那么多地铁站

实现一下新周刊中的操作,生成地铁名词云

def create_wordcloud(df):
    """
    生成地铁名词云
    """
    # 分词
    text = ''
    for line in df['station']:
        text += ' '.join(jieba.cut(line, cut_all=falsE))
        text += ' '
    BACkgroud_Image = plt.imread('rocket.jpg')
    wc = WordCloud(
        BACkground_color='white',
        mask=BACkgroud_Image,
        font_path='C:\Windows\Fonts\华康俪金黑W8.TTF',
        max_words=1000,
        max_font_size=150,
        min_font_size=15,
        prefer_horizontal=1,
        random_state=50,
    )
    wc.generate_from_text(text)
    img_colors = ImageColorGenerator(BACkgroud_ImagE)
    wc.recolor(color_func=img_colors)
    # 看看词频高的有哪些
    process_word = WordCloud.process_text(wc, text)
    sort = sorted(process_word.items(), key=lambda e: e[1], reverse=TruE)
    print(sort[:50])
    plt.imshow(wC)
    plt.axis('off')
    wc.to_file("地铁名词云.jpg")
    print('生成词云成功!')

create_wordcloud(df_station)

展示词云图

 

大佬总结

以上是大佬教程为你收集整理的Python爬虫实战,pyecharts模块,Python实现中国地铁数据可视化全部内容,希望文章能够帮你解决Python爬虫实战,pyecharts模块,Python实现中国地铁数据可视化所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。