Python数据可视化:2024年电影分析_针对猫眼电影评论数据怎么可视化分析

maoyanFont = TTFont(‘maoyan.woff’)
    maoyan_unicode_list = maoyanFont[‘cmap’].tables[0].ttFont.getGlyphOrder()
    maoyan_num_list = []
    base_num_list = [‘.’, ‘3’, ‘0’, ‘8’, ‘9’, ‘4’, ‘1’, ‘5’, ‘2’, ‘7’, ‘6’]
    base_unicode_list = [‘x’, ‘uniF561’, ‘uniE6E1’, ‘uniF125’, ‘uniF83F’, ‘uniE9E2’, ‘uniEEA6’, ‘uniEEC2’, ‘uniED38’, ‘uniE538’, ‘uniF8E7’]
    for i in range(1, 12):
        maoyan_glyph = maoyanFont[‘glyf’][maoyan_unicode_list[i]]
        for j in range(11):
            base_glyph = base_font[‘glyf’][base_unicode_list[j]]
            if maoyan_glyph == base_glyph:
                maoyan_num_list.append(base_num_list[j])
                break
    maoyan_unicode_list[1] = ‘uni0078’
    utf8List = [eval(r"‘\u" + uni[3:] + "’").encode(“utf-8”) for uni in maoyan_unicode_list[1:]]
    utf8last = []
    for i in range(len(utf8List)):
        utf8List[i] = str(utf8List[i], encoding=‘utf-8’)
        utf8last.append(utf8List[i])
    return (maoyan_num_list ,utf8last)


 


**/ 03 / 数据获取**


 


**01  构造请求头**



head = “”"
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:maoyan.com
Upgrade-Insecure-Requests:1
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36
“”"

def str_to_dict(header):
    “”"
    构造请求头,可以在不同函数里构造不同的请求头
    “”"
    header_dict = {}
    header = header.split(‘\n’)
    for h in header:
        h = h.strip()
        if h:
            k, v = h.split(‘:’, 1)
            header_dict[k] = v.strip()
    return header_dict


 


因为索引页和详情页请求头不一样,这里为了简便,构造了一个函数。


 


**02  获取电影详情页链接**



def get_url():
    “”"
    获取电影详情页链接
    “”"
    for i in range(0, 300, 30):
        time.sleep(10)
        url = ‘http://maoyan.com/films?showType=3&yearId=13&sortId=3&offset=’ + str(i)
        host = “”“Referer:http://maoyan.com/films?showType=3&yearId=13&sortId=3&offset=0
        “””
        header = head + host
        headers = str_to_dict(header)
        response = requests.get(url=url, headers=headers)
        html = response.text
        soup = BeautifulSoup(html, ‘html.parser’)
        data_1 = soup.find_all(‘div’, {‘class’: ‘channel-detail movie-item-title’})
        data_2 = soup.find_all(‘div’, {‘class’: ‘channel-detail channel-detail-orange’})
        num = 0
        for item in data_1:
            num += 1
            time.sleep(10)
            url_1 = item.select(‘a’)[0][‘href’]
            if data_2[num-1].get_text() != ‘暂无评分’:
                url = ‘http://maoyan.com’ + url_1
                for message in get_message(url):
                    print(message)
                    to_mysql(message)
                print(url)
                print(‘---------------^^Film_Message^^-----------------’)
            else:
                print(‘The Work Is Done’)
                break


 


**03  获取电影详情页信息**



def get_message(url):
    “”"
    获取电影详情页里的信息
    “”"
    time.sleep(10)
    data = {}
    host = “”“refer: http://maoyan.com/news
    “””
    header = head + host
    headers = str_to_dict(header)
    response = requests.get(url=url, headers=headers)
    u = response.text
    # 破解猫眼文字反爬
    (mao_num_list, utf8last) = get_numbers(u)
    # 获取电影信息
    soup = BeautifulSoup(u, “html.parser”)
    mw = soup.find_all(‘span’, {‘class’: ‘stonefont’})
    score = soup.find_all(‘span’, {‘class’: ‘score-num’})
    unit = soup.find_all(‘span’, {‘class’: ‘unit’})
    ell = soup.find_all(‘li’, {‘class’: ‘ellipsis’})
    name = soup.find_all(‘h3’, {‘class’: ‘name’})
    # 返回电影信息
    data[“name”] = name[0].get_text()
    data[“type”] = ell[0].get_text()
    data[“country”] = ell[1].get_text().split(‘/’)[0].strip().replace(‘\n’, ‘’)
    data[“length”] = ell[1].get_text().split(‘/’)[1].strip().replace(‘\n’, ‘’)
    data[“released”] = ell[2].get_text()[:10]
    # 因为会出现没有票房的电影,所以这里需要判断
    if unit:
        bom = [‘分’, score[0].get_text().replace(‘.’, ‘’).replace(‘万’, ‘’), unit[0].get_text()]
        for i in range(len(mw)):
            moviewish = mw[i].get_text().encode(‘utf-8’)
            moviewish = str(moviewish, encoding=‘utf-8’)
            # 通过比对获取反爬文字信息
            for j in range(len(utf8last)):
                moviewish = moviewish.replace(utf8last[j], maoyan_num_list[j])
            if i == 0:
                data[“score”] = moviewish + bom[i]
            elif i == 1:
                if ‘万’ in moviewish:
                    data[“people”] = int(float(moviewish.replace(‘万’, ‘’)) * 10000)
                else:
                    data[“people”] = int(float(moviewish))
            else:
                if ‘万’ == bom[i]:
                    data[“box_office”] = int(float(moviewish) * 10000)
                else:
                    data[“box_office”] = int(float(moviewish) * 100000000)
    else:
        bom = [‘分’, score[0].get_text().replace(‘.’, ‘’).replace(‘万’, ‘’), 0]
        for i in range(len(mw)):
            moviewish = mw[i].get_text().encode(‘utf-8’)
            moviewish = str(moviewish, encoding=‘utf-8’)
            for j in range(len(utf8last)):
                moviewish = moviewish.replace(utf8last[j], maoyan_num_list[j])
            if i == 0:
                data[“score”] = moviewish + bom[i]
            else:
                if ‘万’ in moviewish:
                    data[“people”] = int(float(moviewish.replace(‘万’, ‘’)) * 10000)
                else:
                    data[“people”] = int(float(moviewish))
        data[“box_office”] = bom[2]
    yield data


 


**/ 04 / 数据存储**


 


**01  创建数据库及表格**



db = pymysql.connect(host=‘127.0.0.1’, user=‘root’, password=‘774110919’, port=3306)
cursor = db.cursor()
cursor.execute(“CREATE DATABASE maoyan DEFAULT CHARACTER SET utf8mb4”)
db.close()



db = pymysql.connect(host=‘127.0.0.1’, user=‘root’, password=‘774110919’, port=3306, db=‘maoyan’)
cursor = db.cursor()
sql = ‘CREATE TABLE IF NOT EXISTS films (name VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, country VARCHAR(255) NOT NULL, length VARCHAR(255) NOT NULL, released VARCHAR(255) NOT NULL, score VARCHAR(255) NOT NULL, people INT NOT NULL, box_office BIGINT NOT NULL, PRIMARY KEY (name))’
cursor.execute(sql)
db.close()


 


其中票房收入数据类型为BIGINT(19位数),最大为18446744073709551615。


 


INT(10位数),最大为2147483647,达不到36亿(3600000000)。


 


**02  数据存储**



def to_mysql(data):
    “”"
    信息写入mysql
    “”"
    table = ‘films’
    keys = ', '.join(data.keys())
    values = ‘, ‘.join([’%s’] * len(data))
    db = pymysql.connect(host=‘localhost’, user=‘root’, password=‘774110919’, port=3306, db=‘maoyan’)
    cursor = db.cursor()
    sql = ‘INSERT INTO {table}({keys}) VALUES ({values})’.format(table=table, keys=keys, values=values)
    try:
        if cursor.execute(sql, tuple(data.values())):
            print(“Successful”)
            db.commit()
    except:
        print(‘Failed’)
        db.rollback()
    db.close()


 


最后成功存储数据


![](https://img-blog.csdnimg.cn/20190612210221712.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


 


**/ 05 / 数据可视化**


 


可视化源码:


链接:https://pan.baidu.com/s/18vCPo-rbB8qh4F9mdxpsqA   
 提取码:r5qy 


 


**01  电影票房TOP10**


 


![](https://img-blog.csdnimg.cn/20190612211602304.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


还剩一个多月,不知道榜单上会不会有新成员。最近「毒液」很火,蛮有希望。


 


**02  电影评分TOP10**


![](https://img-blog.csdnimg.cn/20190612211616516.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


这里就得吐槽一下pyecharts,坐标转换后,坐标值名称太长就会被遮挡,还需改进呢~


 


**03  电影人气TOP10**


![](https://img-blog.csdnimg.cn/20190612211629808.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


茫茫人海之中,相信一定也有大家的身影,我也是其中的一员!!!


 


****04  每月****电影****上映数量****


![](https://img-blog.csdnimg.cn/20190612211644824.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


每月上映数好像没什么大差距,7月最少,难道是因为天气热?


 


********05  每月********电影********票房********


![](https://img-blog.csdnimg.cn/20190612211703213.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


这里就看出春节档电影的威力了,金三银四、金九银十,各行各业的规律,电影行业也不例外。


 


上一张图我们知道7月份电影上新最少,票房反而是第二。


 


这里看了下数据,发现有「我不是药神」「西虹市首富」「邪不压正」「摩天营救」「狄仁杰之四大天王」几部大剧撑着。


 


****************06  各国家电影数量TOP10****************


![](https://img-blog.csdnimg.cn/20190612211726524.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)


 


原来中国电影这么高产的,可是豆瓣TOP250里又有多少中国电影呢?深思!!!


 


如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费**学习**大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。



### 一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。



![](https://img-blog.csdnimg.cn/img_convert/9f49b566129f47b8a67243c1008edf79.png)

### 二、学习软件



工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。



![](https://img-blog.csdnimg.cn/img_convert/8c4513c1a906b72cbf93031e6781512b.png)



### 三、全套PDF电子书

书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。

![](https://img-blog.csdnimg.cn/img_convert/eec417a3d4d977b313558a11d3c13e43.png)



### 四、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。



![](https://img-blog.csdnimg.cn/img_convert/ec690501ea1dbe2cb209cbf4013c2477.png)  

![](https://img-blog.csdnimg.cn/img_convert/3eaeaa6747419c9d86c72e0d10d0a6a2.png)



### 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。



![](https://img-blog.csdnimg.cn/img_convert/252731a671c1fb70aad5355a2c5eeff0.png)



### 五、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

![](https://img-blog.csdnimg.cn/img_convert/6c361282296f86381401c05e862fe4e9.png)

成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值