生活札记

Python学习笔记 - 进阶(二)

copylian    1 评论    12346 浏览    2022.09.15

Python由荷兰数学和计算机科学研究学会的吉多·范罗苏姆于1990年代初设计,作为一门叫做ABC语言的替代品。Python提供了高效的高级数据结构,还能简单有效地面向对象编程。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的编程语言,随着版本的不断更新和语言新功能的添加,逐渐被用于独立的、大型项目的开发。

Python解释器易于扩展,可以使用C语言或C++(或者其他可以通过C调用的语言)扩展新的功能和数据类型。Python也可用于可定制化软件中的扩展程序语言。Python丰富的标准库,提供了适用于各个主要系统平台的源码或机器码。 

2021年10月,语言流行指数的编译器Tiobe将Python加冕为最受欢迎的编程语言,20年来首次将其置于Java、C和JavaScript之上。

官网:https://www.python.org/downloads/

教程:https://www.bilibili.com/video/BV1yY4y1w7r8

教程:https://www.bilibili.com/video/BV1EE41187jY

编程语言排行:https://www.tiobe.com/tiobe-index/


1、基础

# Python关键字

import keyword # 关键字

import this # python 作者禅语


# 禅语

print(this)


# 保留关键字

print(keyword.kwlist)

# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


# 格式化

str = "{0}{1}{0}".format("嗨呀", 666)

print(str)


str2 = "{name}{age}".format(name="飓风呀", age=20)

print(str2)


# map ** 展开

map = {"name":"飓风呀", "age":20}

str3 = "{name}{age}".format(**map)

print(str3)


# f方法格式化

str4 = "飓风呀"

print(f"{str4:*>10}")

print(f"{str4:*<10}")

print(f"{str4:*^10}")


# f方法多个输出

title = "请假条"

name = "张老师"

message = (

    f"{title:-^15}\n"

    f"To:{name}"

)

print(message)


# 多个输出

print(1,2,3,4)

print(1,2,3,4,end="\n\t")

print(1,2,3,4,sep="#")


# 复数complex

a = complex(3, 4)

# a = 3 + 4j

print(a)


# 运算符号:is、is not 判断是否是引用自同一个对象:id(x) == id(y),内存地址是否一致

a = 100

b = 100

print(a is b)


# for i in range(start,stop,step),不包含stop

for i in range(1, 10, 2):

    print(i)


2、字符串

# 字符串


# 多行字符串

str = """

    a


    b

    c

"""

print(str)


# 字符串切片:s[start:stop:step] 不包含stop

str1 = "Hello World!"

print(str1[1:5:3])


# 统计次数

print(str1.count("l"))


3、list列表

# list列表数组


# list 转成list

arr = list(range(1,10))

print(arr)


arr = list("Jufengya 飓风呀")

print(arr)


# list 切片 [start:stop:step] 不包含stop

arr = [10,20,30,40,50]

print(arr[0:2:1])


# max()、min()、sum():可转换的同类型,不同类型则报错

print(max(arr))

print(min(arr))

print(sum(arr))


# list + list 类似extend

arr1 = [1,2,3]

arr2 = [4,5,6]

arr3 = arr1 + arr2

print(arr3)


# list * 重复N次

print(arr3 * 3)


# in、not in

print(1 in arr3)


# 多维列表

arr4 = [[1,2,3], [4,5,6], [7,8,9]]

print(arr4)


# 赋值、浅拷贝copy()、深拷贝 copy.deepcopy()

import copy

num1 = [1,2,3]

num2 = num1 # 赋值,拷贝内存地址

num3 = num1.copy() # 浅拷贝:只能拷贝列表的一级元素,复制了嵌套的可变数据类型的地址

num4 = copy.deepcopy(num1)  # 深拷贝:能拷贝所有层级的元素,复制了嵌套的可变数据类型的元素

print(id(num1))

print(id(num2))

print(id(num3))

num1.append(1)

print(id(num4))


4、tuple元组

# tuple元组:不可变,如果是可变元素可改,操作类似于列表

mylist = [1,2] # 可变

tup = (10,20,30, mylist)

# tup[1] = 21  # 报错

print(tup)

mylist[1] = 10

print(tup) 


微信图片_20220915172328.png


5、函数 def function

# 函数function


# 函数在定义时:* :将多个变量进行打包,变成元组

def testfunction(name, age=20, *args):

    print(f"{name}:{age}")

    print(args)


# 函数在定义时:** 作用:将多个变量进行打包,变成字典

def testfunction2(name, age=20, **kwargs):

    print(f"{name}:{age}")

    print(kwargs)


# *args 与 **kwargs 参数,如果在其他参数前面就必须使用键值对方式

def testArgs(*args, name, age=20, **kwargs):

    print(f"{name}:{age}")

    print(args)

    print(kwargs)


# * 可变参数

def testArgs2(name, age=20, * , a, b):

    print(f"{name}:{age}")

    print(a)

    print(b)


# 执行函数

testfunction("飓风呀",1,3,3,4,45,5)

testfunction2("飓风呀", 1, sex="男", colleague="清华北大")


# * 的作用是把参数解构出来

rate = [1,2,3,4]

# rate = (1,2,3,4)

# rate = {1,2,3,45}

testfunction("飓风呀",28, *rate)


# ** 的作用是把字典参数解构出来

rate = {"sex": "男", "colleague": "清华北大"}

testfunction2("飓风呀",28, **rate)


# 如果在其他参数前面就必须使用键值对方式

testArgs(1,2,3,name="飓风啊", age=10, dd=1,xx=2)


# * 做了一个占位符,a、b必须是键值对

testArgs2("飓风呀",10,a=1,b=10)


6、全局变量、局部变量

# 全局变量、局部变量

# 全局变量

a = 10


# 函数

def test1():

    global a # global 声明全局

    a = 20

    b = 30

    print(a,b)

    print(locals())  # locals() 返回当前作用域的变量

    print(globals())  # globals() 返回所有全局变量


# 执行函数

test1()

print(a)


# 不可变参数修改值不变,可变参数传递的是一个地址,改变值则会变

def test2(a, b):

    a = 20

    b.append("c")

    print(a, b, id(b))



# 执行函数

x = 10

y = ["a", "b"]

test2(x,y)

print(x,y,id(y))


6、文件操作

# 文件

# open(文件, 模式, 编码)

# 写入

f = open("test.txt", "w", encoding="utf-8")

f.write("飓风呀\n") # 写入

data = ["飓风呀1\n","飓风呀2\n","飓风呀3\n"]

f.writelines(data)  # 多行写入

f.flush() # 刷新缓冲区

f.close()


# 读取

f = open("test.txt", "r+", encoding="utf-8")

data = f.read(5) # read(字符个数)

print(data)


f.seek(0)  # seek() 设置光标的位置,指的是字节位置

line = f.readline() # 读取行

print(line)


print(f.tell())  # tell() 光标的位置,指的是字节位置


lines = f.readlines() # 将数据按行读取到list中

print(lines)


f.truncate(6) # 清空光标后的数据


f.close()


# 读取二进制

f1 = open("head.jpg", "rb")

f2 = open("head_copy.jpg", "wb")

while True:

    data = f1.read(100) # 每次读取100

    if data: # 读取结束 b""

        f2.write(data) # 写入

    else:

        break


f1.close()

f2.close()


7、打印包信息

# 打印包信息

import importtestA

print(help(importtestA))


8、爬虫

安装pip:前提:必须安装了pip,如果没安装,可以下载https://pypi.python.org/pypi/pip#downloads,然后解压,最后进入安装包,执行python setup.py 安装【默认安装在D:\py\Scripts中】

使用pip -help可查看pip的一些常用命令

然后使用:pip install packageName 来安装

BeautifulSoup文档:https://blog.csdn.net/m0_37623485/article/details/88324296

xlwt:https://blog.csdn.net/qq_45464895/article/details/122445117


# 爬虫

from bs4 import BeautifulSoup  # 网页解析,获取数据

import re # 正则表达式

import urllib.request, urllib.error, urllib.parse  # 制定URL,获取网页数据

import xlwt # excel操作

import sqlite3 # sqlite3数据库操作

import os


# 定义正则

re_sort = re.compile(r'<em class="">(\d+)</em>')

re_link = re.compile(r'<a.*href="(.*?)">')

re_imgsrc = re.compile(r'<img.*src="(.*?)"', re.S # re.S 匹配包括换行在内的所有字符

re_title = re.compile(r'<span class="title">(.*?)</span>')

re_score = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')

re_judge = re.compile(r'<span>(\d*)人评价</span>')

re_inq = re.compile(r'<span class="inq">(.*?)</span>')

re_content = re.compile(r'<p class="">(.*?)</p>', re.S)


# 模拟请求,头部信息

headers = {

    "User-Agent": "Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"

}


# 请求网址

def askUrl(url):

    # 返回html

    html = ""


    # 请求

    request = urllib.request.Request(url, headers=headers)


    # 处理错误

    try:

        response = urllib.request.urlopen(request)

        html = response.read().decode("utf-8")

    except urllib.error.URLError as e:

        if hasattr(e, "code"):

            print(e.code)

        if hasattr(e, "reason"):

            print(e.reason)

    # 返回数据

    return html


# 抓取网页

def getData(url):

    # 开始抓取

    print("开始抓取...")


    # Get 请求

    # response = urllib.request.urlopen("http://www.baidu.com/")

    # response = response.read().decode("utf-8")

    # f = open("index.html", "w", encoding="utf-8")

    # f.write(response)

    # f.close()


    # Post 请求

    # sendData = bytes(urllib.parse.urlencode({"name":"飓风呀"}), encoding="utf-8")

    # response = urllib.request.urlopen("http://httpbin.org/post", data=sendData)

    # response = response.read().decode("utf-8")

    # print(response)


    # 超时处理

    # try:

    #     sendData = bytes(urllib.parse.urlencode(

    #         {"name": "飓风呀"}), encoding="utf-8")

    #     response = urllib.request.urlopen("http://httpbin.org/post", data=sendData, timeout=0.01)

    #     response = response.read().decode("utf-8")

    #     print(response)

    # except Exception as e:

    #     print("time out!")


    # Get 请求

    # response = urllib.request.urlopen("http://www.baidu.com/")

    # print(response.status) # 状态码

    # print(response.getheader("Content-Type")) # 返回信息

    # print(response.getheader("Server"))  # 返回信息


    # 模拟请求

    # url = "http://httpbin.org/post" # 请求url

    # url = "https://movie.douban.com/"  # 请求url,没有模拟header返回爬虫418状态码

    # headers = {

    #     "user-agent": "Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"

    # } # 头部信息

    # sendData = bytes(urllib.parse.urlencode({"name": "飓风呀"}), encoding="utf-8") # 发送的数据

    # request = urllib.request.Request(url=url, headers=headers, data=sendData, method="POST")

    # response = urllib.request.urlopen(request)

    # response = response.read().decode("utf-8")

    # print(response)


    # 返回数据

    datalist = []


    # 循环处理

    for i in range(0, 10):


        # 获取网页信息

        html = askUrl(url + str(i * 25))


        # 处理解析返回的html

        bs = BeautifulSoup(html, "html.parser")  # BeautifulSoup 返回整个html DOM文档


        # 1、文档

        # print(bs) # 整个文档

        # print(bs.name) # document

        # print(bs.title) # 元素标签

        # print(bs.title.string) # 元素标签值

        # print(bs.a.attrs) # 元素属性


        # 2、文档遍历

        # print(bs.head.contents)


        # 3、文档搜索

        # 1)、find_all()

        # print(bs.find_all("a")) # 字符串过滤

        # print(bs.find_all(re.compile("span"))) # 正则表达式

        # print(bs.find_all(name_is_exists)) # 通过函数来过滤

        # print(bs.find_all())


        # print(bs.find_all(id="dale_movie_top250_bottom_right")) # kwargs 参数

        # print(bs.find_all(class_="entrance-qrcode")) # class_ 指定

        # print(bs.find_all(class_=True))  # class_ 全部


        # print(bs.find_all(text="豆瓣")) # 文本

        # print(bs.find_all(text=["豆瓣", "电影"])) # 文本

        # print(bs.find_all(text=re.compile("\d")))  # 文本正则


        # print(bs.find_all("a", limit=2))  # limit 限制


        # 2)、select() css选择器

        # print(bs.select("title")) # 属性

        # print(bs.select("head title"))  # 子标签

        # print(bs.select("title ~ meta"))  # 兄弟标签

        # print(bs.select("p[class='quote']"))  # 属性查找

        # print(bs.select(".entrance-qrcode")) # css 类

        # print(bs.select("#dale_movie_top250_bottom_right")) # css ID标签

        # print(bs.select("title")[0].get_text()) # 获取内容


        # 4、正则表达式

        # 1)、方法:re.search()、re.match()、re.findall()、re.split()、re.finditer()、re.sub()

        # 2)、模式:r.l:大小写不敏感、re.L:本地化识别匹配、re.M:多行匹配,影响$ 很 ^、re.S:使 . 匹配包括换行在内的所有字符、re.U:根据Unicode字符集解析字符,这个影响标识 \w \W \b \B、re.X:更灵活的方法将正则表达式写得更容易理解

        

        # 3)、实践:

        # print(re.search("AA", "abcdAAbbcc"))  # 参数1:规则,参数2:模板

        # print(re.findall("[A-Z]", "ABcdEfghIjK")) # 参数1:规则,参数2:模板

        # print(re.sub("a", "A", "AbcdEfGAcaaA")) # 替换 a 替换成 A


        # 建议在正则表达是中,被比较的字符串加上r,不用担心转义字符的问题

        # a = r"\abcd\aa\'"

        # print(a)


        # 查找到对应的dom

        list = bs.find_all('div', class_="item")

        for item in list:


            # 返回数据

            data = []


            # print(item)

            # 转成字符串

            item = str(item)


            # 获取排名

            sort = re.findall(re_sort, item)

            data.append(sort[0])


            # 获取链接

            link = re.findall(re_link, item)

            data.append(link[0])


            # 获取图片

            imgsrc = re.findall(re_imgsrc, item)

            data.append(imgsrc[0])


            # 获取标题

            title = re.findall(re_title, item)

            if len(title) >= 2:

                # 中文名

                data.append(title[0])


                # 其他国家名称

                otitle = title[1].replace("/", "")

                data.append(otitle)

            else:

                # 中文名

                data.append(title[0])


                # 其他国家名称

                data.append("")


            # 评分

            score = re.findall(re_score, item)

            data.append(score[0])


            # 评价人数

            judge = re.findall(re_judge, item)

            data.append(judge[0])


            # 概述

            inq = re.findall(re_inq, item)

            if len(inq) != 0:

                data.append(inq[0].replace("。", ""))

            else:

                data.append("")


            # 内容

            content = re.findall(re_content, item)

            content = re.sub("<br(\s+)?/>(\s+)?", "", content[0])  # 去除<br>

            content = re.sub("/", "", content)  # 去除 / 

            content = content.strip() # 去除空格

            data.append(content)


            # 数据压入返回数据

            datalist.append(data)

        

    # 打印数据

    # print(datalist)


    # 返回数据

    return datalist


# 根据函数搜索

def name_is_exists(tag):

    return tag.has_attr("name")


# 保存数据

def saveData(saveName, datalist):

    # # xlwt 操作 excel

    # book = xlwt.Workbook(encoding='utf-8', style_compression = 0) # 创建workbook对象

    # sheet = book.add_sheet("sheet666", cell_overwrite_ok = True) # 添加sheet

    # sheet.write(0, 0, "Hello World!") # 写入数据

    # book.save(path)  # 保存


    # # xlwt 操作 excel

    # book = xlwt.Workbook(encoding='utf-8', style_compression = 0) # 创建workbook对象

    # sheet = book.add_sheet("99乘法", cell_overwrite_ok = True) # 添加sheet

    # for i in range(0, 9):

    #     for j in range(0, i+1):

    #         sheet.write(i, j, "%d * %d = %d" % (i+1, j+1, (i+1)*(j+1)))  # 写入数据

    # book.save("99乘法.xls")  # 保存


    # 创建保存excel

    book = xlwt.Workbook(encoding='utf-8', style_compression = 0) # 创建workbook对象

    sheet = book.add_sheet(saveName, cell_overwrite_ok=True)  # 添加sheet


    # 写入表头

    col = ["排名", "详情链接", "图片链接", "中文名", "外国名", "评分", "评价数", "概况", "相关信息"]

    for i in range(0, len(col)):

        sheet.write(0, i, col[i])  # 写入数据

    

    # 写入内容

    for i in range(0, len(datalist)):

        data = datalist[i]

        for j in range(0, len(data)):

            sheet.write(i+1, j, data[j])  # 写入数据


    # 保存

    book.save(saveName + ".xls")


    # 输出

    print("抓取完成!")


# 保存数据 Sql

def saveDataSql(name, datalist):

    # 初始化数据库

    # init_db()


    # 3、插入

    conn = sqlite3.connect(name + ".db")  # 连接数据库

    c = conn.cursor() # 获取游标


    # 循环处理数据

    for data in datalist:

        sql = 'insert into ' + name + ' (sort, link, imgsrc, name, ename, score, judge, inq, content) values('+data[0]+', "'+data[1]+'", "'+data[2]+'", "'+data[3]+'", "'+data[4]+'", '+data[5]+', '+data[6]+', "'+data[7]+'", "'+data[8] +'"); '

        # print(sql)

        print("抓取:"+data[3]+" 成功")

        c.execute(sql) # 执行sql

        conn.commit() # 提交数据

    c.close() # 关闭游标

    conn.close() # 关闭数据库


    # 输出

    print("抓取完成!")


# 初始化数据库

def init_db():

    # 连接数据库

    conn = sqlite3.connect("movie.db")

    c = conn.cursor()  # 获取游标

    sql = '''

        create table movie(

            id INTEGER primary key autoincrement,

            sort int,

            link text,

            imgsrc text,

            name vachart(50),

            ename vachart(100),

            score numeric,

            judge numeric,

            inq text,

            content text

        );

    '''

    c.execute(sql)  # 执行sql

    conn.commit()  # 提交数据

    conn.close()  # 关闭数据库


# 主函数

def main():

    # url

    url = "https://movie.douban.com/top250?start="  # 请求url,没有模拟header返回爬虫418状态码


    # 解析数据、爬取网页

    datalist = getData(url)


    # 保存数据

    # saveName = "豆瓣电影top250"

    # saveData(saveName, datalist)


    # 保存数据 Sql

    saveDataSql("movie", datalist)


# sqlite3 数据库测试

def sqlite():

    # 1、连接数据库

    # conn = sqlite3.connect("test.db")

    # print("链接数据库")


    # 2、创建表

    # conn = sqlite3.connect("test.db") # 连接数据库

    # c = conn.cursor() # 获取游标

    # sql = '''

    #     create table company(

    #         id int primary key not null,

    #         name text not null,

    #         age int not null,

    #         address varchar(50) not null,

    #         salary real

    #     );

    # '''

    # c.execute(sql) # 执行sql

    # conn.commit() # 提交数据

    # conn.close() # 关闭数据库


    # 3、插入

    # conn = sqlite3.connect("test.db") # 连接数据库

    # c = conn.cursor() # 获取游标

    # sql = '''

    #    insert into company (id, name, age, address, salary) values(2, "飓风呀2", 22, "福建厦门2", 20.00);

    # '''

    # c.execute(sql) # 执行sql

    # conn.commit() # 提交数据

    # conn.close() # 关闭数据库


    # 4、查询

    conn = sqlite3.connect("test.db") # 连接数据库

    c = conn.cursor() # 获取游标

    sql = '''

       select * from company

    '''

    data = c.execute(sql) # 执行sql

    for row in data:

        print(row)

    conn.close() # 关闭数据库


# 爬取图片

def saveFiles(savePath):

    # 开始抓取

    print("开始抓取...")


    # 验证目录是否存在,不存在则新建

    if os.path.exists(savePath) == False:

        # 创建多级目录

        os.makedirs(savePath, mode=0o777)


    # 查询数据图片url

    conn = sqlite3.connect("movie.db") # 连接数据库

    c = conn.cursor() # 获取游标

    sql = '''

        select id,imgsrc from movie order by sort asc

    '''

    data = c.execute(sql)  # 执行sql


    # 抓取图片

    for row in data:


        # 保存路径

        row_split = row[1].split(".")

        openPath = savePath + "/" + str(row[0]) + "." + row_split[-1]


        # 请求

        request = urllib.request.Request(row[1], headers=headers)


        # 处理错误

        try:

            # 获取远程数据

            response = urllib.request.urlopen(request)

            imgdata = response.read()


            # 写入文件

            f = open(openPath, "ab")

            f.write(imgdata)

            f.close() # 关闭

            print("抓取文件:" + openPath + " 成功")


        except urllib.error.URLError as e:

            if hasattr(e, "code"):

                print(e.code)

            if hasattr(e, "reason"):

                print(e.reason)


    c.close() # 关闭

    conn.close() # 关闭数据库


    # 抓取图片、保存到对应目录

    print("抓取完成!")


# 执行主函数

if __name__ == '__main__':

    # main()

    # sqlite()


    # 保存目录

    savePath = "./static/images/poster"

    saveFiles(savePath)



# 测试爬取json

# import bs4  # 网页解析,获取数据

import json

import urllib  # 制定URL,获取网页数据

import urllib.request

import urllib.error

import urllib.parse  # 制定URL,获取网页数据


# 模拟请求,头部信息

headers = {

    "User-Agent": "Mozilla/5.0 (Windows NT 10.0 Win64 x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"

}


# 请求网址

def askUrl(url):

    # 返回html

    html = ""


    # 请求

    request = urllib.request.Request(url, headers=headers)


    # 处理错误

    try:

        response = urllib.request.urlopen(request)

        html = response.read().decode("utf-8")

        # print(html)

    except urllib.error.URLError as e:

        if hasattr(e, "code"):

            print(e.code)

        if hasattr(e, "reason"):

            print(e.reason)

    # 返回数据

    return html


# 主函数

def main():

    url = "https://www3.nhk.or.jp/news/json16/link/top/top_link.json?_=1663663507774"

    data = askUrl(url)

    # print(data)


    # 转成json

    rdata = json.loads(data)

    print(rdata)


# 执行

if __name__ == '__main__':

    main()


9、可视化:网页、图表、分词

echarts可视化图表库:https://echarts.apache.org/zh/index.html

词云:wordcloud:https://amueller.github.io/word_cloud/


# 导入 Flask、Jinjia2

from flask import Flask # 网页http处理

from flask import render_template

from flask import request

import sqlite3


# 词云

import jieba # 分词

from matplotlib import pyplot as plt  # 绘图,数据可视化

from wordcloud import WordCloud # 词云

from PIL import Image # 图片处理

import numpy as np # 矩阵运算


# 实例化Flask

app = Flask(__name__)


# 定义路由

@app.route('/')

def hello():

    return "Hello World"


# 带参数

@app.route('/user/<name>')

def user(name):

    return "Hello %s" % name


# 带参数

@app.route('/info/<int:id>')

def info(id):

    return "Info %d" % id


# 模板渲染

@app.route('/teplateinfo')

def teplateinfo():

    # 定义参数

    name = "Python"

    lang = ["Python", "Golang", "PHP"]

    person = {

        "name":"飓风呀",

        "sex":"女",

        "age":28

    }

    return render_template("test/index.html", name=name,, person=person)


# 登录

@app.route("/login")

def login():

    return render_template("test/login.html")


# 登录结果

@app.route("/login_result", methods=["POST", "GET"])

def login_result():

    if request.method == "POST":

        print(request.form)

        return render_template("test/login_result.html", data=request.form)


# 图表

@app.route("/echarts")

def echarts():

    # 分数

    score = []


    # 分数数量

    score_count = []


    # 查询统计评分

    conn = sqlite3.connect("movie.db")  # 连接数据库

    c = conn.cursor()  # 获取游标

    sql = '''

       select score,count(id) from movie group by score order by score asc

    '''

    data = c.execute(sql)  # 执行sql

    for row in data:

        # score.append(str(row[0])) # 转字符串类型,tojson解析

        score.append(row[0])

        score_count.append(row[1])


    c.close() # 关闭

    conn.close()  # 关闭数据库


    # 渲染模板

    print(score)

    print(score_count)

    return render_template("test/echarts.html", score=score, score_count=score_count)


# 词云

@app.route("/cloud")

def cloud():

    # 词语

    word = ""


    # 1、查询

    conn = sqlite3.connect("movie.db")  # 连接数据库

    c = conn.cursor()  # 获取游标

    sql = '''

       select inq from movie where inq != ''

    '''

    data = c.execute(sql)  # 执行sql

    for row in data:

        word += row[0]


    c.close()  # 关闭

    conn.close()  # 关闭数据库


    # 2、分词

    cut = jieba.cut(word)

    words = " ".join(cut)

    print(len(words))


    # 3、生成图片遮罩

    # 打开图片

    img = Image.open("./static/assets/images/cloud.png")


    # 图片转成数组

    img_array = np.array(img)


    # 词云

    wc = WordCloud(

        background_color="white",

        mask=img_array,

        font_path="msyh.ttc",

        width=640,

        height=640

    )

    wc.generate_from_text(words) # 处理分词


    # 4、绘制生成图片

    plt.switch_backend('agg')  # agg模式

    plt.figure(1)

    plt.imshow(wc) # 使用图片遮罩

    plt.axis("off") # 是否显示坐标

    # plt.show() # 显示


    # 输出保存图片

    img = "./static/assets/images/cloud_new.png"

    plt.savefig(img,dpi=500)


    # 渲染

    return render_template("test/cloud.html",img=img)


# 执行

if __name__ == "__main__":

    # debug模式

    app.run(debug=True)


# html模板输出

{% for key,value in data.items() %}

        {{ key }} : {{ value }}<br>

{% endfor %}


<p>Name:{{ name }}</p>

<p>Lang:{% for i in lang %} {{ i }} {% endfor %}</p>

<p>Person:{% for i,v in person.items() %} {{ i }} : {{ v }} {% endfor %}</p>


<form action="{{ url_for('login_result') }}" method="POST">

        <div>

            姓名:<input name="name" id="name" type="text" placeholder="请输入姓名">

        </div>

        <div>

            <input id="submit" type="submit" value="提交">

        </div>

</form>


data: {{ score|tojson }}


只袄早~~~
感谢你的支持,我会继续努力!
扫码打赏,感谢您的支持!

文明上网理性发言!