Python数据分析<12306信息可视化>

文章详细描述了如何使用Python的requests和pandas库从12306网站抓取并处理火车站信息,通过数据处理和可视化工具matplotlib展示车站数量Top10城市,同时解决了中文显示问题。在数据存储过程中,注意到了车站代码可能出现重复,从而调整了数据结构以避免信息丢失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

12306信息可视化


url=https://kyfw.12306.cn/otn/resources/js/framework/station_name.js
通过访问网站发现,目标网站校验IP地址,以及协议头是否完全
访问结果部分如下:


@bjb|北京北|VAP|beijingbei|bjb|0|0357|北京|||@bjd|北京东|BOP|beijingdong|bjd|1|0357|北京|||@bji|北京|BJP|beijing|bj|2|0357|北京|||@bjn|北京南|VNP|beijingnan|bjn|3|0357|北京|||@bjx|北京大兴|IPP|beijingdaxing|bjdx|4|0357|北京|||@bjx|北京西|BXP|beijingxi|bjx|5|0357|北京|||@bjy|北京朝阳|IFP|beijingchaoyang|bjcy|6|0357|北京|||@cqb|重庆北|CUW|chongqingbei|cqb|7|1717|重庆|

发现数据

根据比对发现,发现数据格式存储为:
@bjb|北京北|VAP|beijingbei|bjb|0|0357|北京|
总结格式为:
@+车站代码+车站名称+...+拼音+...+...+所属城市

代码实现

数据处理

  1. 通过requests包进行网页访问
import requests

url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
data = requests.get(url).text
if not data:
    print('获取数据失败')
print(data)
  1. 通过获取数据后,将数据分割为分类数据
station_data = data.split('=')[-1]
station_name = station_data.strip("='@")
station_name = station_name.rstrip("';")
station_arr = station_name.split('@')
if not station_arr:
    print('获取数据失败')
station_dict = {}
print(station_arr)
  1. 将数据分类完成后,取出需要数据进行归类,并且使用pd库存放到Excel中
import pandas as pd

for station in station_arr:
    info = station.split('|')
    station_code = info[0]
    station_name = info[1]
    station_city = info[7]
    station_dict[station_code] = {
        'Station Name': station_name,
        'station_City': station_city
    }

df = pd.DataFrame.from_dict(station_dict, orient='index').reset_index()

df.columns = ['Station Code', 'Station Name', 'station_City']

print(df)

数据可视化

  1. 将数据进行可视化,使用bar图进行展示
import matplotlib.pyplot as plt

city_count = df['station_City'].value_counts().nlargest(10)
city_count.plot(kind='bar')
plt.xlabel('城市')
plt.ylabel('数量')
plt.title('车站数量Top10城市')
plt.show()

image.png
5. 发现plt打印不了中文,通过查看代码,认为是字体问题或者编码问题

city_count = df['station_City'].value_counts().nlargest(10)
city_count.plot(kind='bar')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('城市')
plt.ylabel('数量')
plt.title('车站数量Top10城市')
plt.show()

image.png
6. 运行之后发现与原始数据不一致, 通过对于前面代码进行审查

可能原因:

  1. requests时候数据没有获取全

  2. 分割数据时候分割错误

  3. 存储数据时候格式有问题

  4. 逐步进行调试, 逐步检查变量值

在下面代码部分变量存储时候发现问题

for station in station_arr:
    info = station.split('|')
    station_code = info[0]
    station_name = info[1]
    station_city = info[7]
    station_dict[station_code] = {
        'Station Name': station_name,
        'station_City': station_city
    }

上述代码中, station_dict作为字典进行存储时候, 时候station作为键, 根据以往经验认为key_code应该是唯一的,但是在此网站中,存在重复的代码, 字典存入数据时候会造成值的覆盖, 导致失去部分值

  1. 修改代码,将字典键进行更改,使用车站名作为key_code
for station in station_arr:
    info = station.split('|')
    station_code = info[0]
    station_name = info[1]
    station_city_code=info[6]
    station_city = info[7]

    station_dict[station_name] = {
        'Station_code': station_code,
        'station_City': station_city,
        'station_city_code':station_city_code,
    }
  1. 再次运行全部代码, 得到正确结果
import requests
import pandas as pd
import matplotlib.pyplot as plt

def get_station_code():
    url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js'
    requests.packages.urllib3.disable_warnings()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
        ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
    }
    data = requests.get(url).text
    if not data:
        print('获取数据失败')
        return None
    # @bjb|北京北|VAP|beijingbei|bjb|0|0357|北京|
    station_data = data.split('=')[-1]
    station_name = station_data.strip("='@")
    station_name = station_name.rstrip("';")
    station_arr = station_name.split('@')

    station_dict = {}

    for station in station_arr:
        info = station.split('|')
        station_code = info[0]
        station_name = info[1]
        station_city_code=info[6]
        station_city = info[7]

        station_dict[station_name] = {
            'Station_code': station_code,
            'station_City': station_city,
            'station_city_code':station_city_code,
        }

    df = pd.DataFrame.from_dict(station_dict, orient='index').reset_index()
    df.columns = ['Station Name','Station Code', 'Station City','Station City Code']

    city_count = df['Station City'].value_counts().nlargest(10)
    city_count.plot(kind='bar')
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.xlabel('城市')
    plt.ylabel('数量')
    plt.title('Top 10')
    plt.show()

    df.to_excel("station_code.xlsx", index=False)

get_station_code()

在这里插入图片描述

【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 3、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于Python编写的中国城市轨道交通数据可视化分析项目源码+项目说明.zip ## 概述 > - 本项目是一个基于 Python 的简单数据可视化分析的小Demo。通过这个项目可以练习使用Python数据可视化分析相关的强大的库和模块,练习绘制简单的GUI界面并且连接数据库,更加深了对Python语言的学习和拓展。本项目也可作为学校的大作业、大实验实践或者课程设计等的选题项目。 > - 本项目通过多线程爬虫获取了高德地图中的中国轨道交通的一些数据信息,高德地图这个权威的网也保证了数据的完整可靠性,然后进行了一些简单并且有趣的数据可视化分析,另外还设计了一个GUI界面,查询数据库或者文件中的一些信息。 > > - 如发现文档中或者源代码中有错误,欢迎大家在 `Issues` 中研究讨论,欢迎大家 `Fork` 和 `Pull requests` 改善代码,十分感谢! ## 使用语言 - Python 3 ## 主要技术 * **网络编程** * **多线程** * **文件操作** * **数据库编程** * **GUI** * **数据分析** ## 导入的库和模块 ```python import json import requests from bs4 import BeautifulSoup import sqlite3 import threading import tkinter as tk from tkinter import scrolledtext import pandas as pd from pyecharts import Line, Bar, Geo import numpy as np from wordcloud import WordCloud, ImageColorGenerator import jieba import matplotlib.pyplot as plt import seaborn as sns ``` ## 项目整体思路 1. 网页分析 2. 多线程爬虫爬取信息 3. 数据保存至文件中和数据库中 4. 利用 tkinter 绘制 GUI 界面,实现查询线路和点两个功能 5. 数据可视化分析 (1)直接控制台显示分析结果 (2)绘制中国地图、柱状图等,生成 .html 文件 (3)绘制词云 (4)绘制柱状图、饼状图、折线图、散点图、双变量图等,生成 .png 文件 ## 运行 - 分别运行`src`文件夹中的`.py`文件即可 ## 部分运行结果样例 .....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DDD-HHY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值