1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Python 萬能代碼模版:數(shù)據(jù)可視化篇

        共 5696字,需瀏覽 12分鐘

         ·

        2021-09-19 23:46

        閱讀本文大概需要6分鐘

        你好,我是悅創(chuàng)。


        上一篇,我寫了:Python 萬能代碼模版:爬蟲代碼篇 接下來,是第二個萬能代碼,數(shù)據(jù)可視化篇。

        其實(shí),除了使用 Python 編寫爬蟲來下載資料, Python 在數(shù)據(jù)分析和可視化方面也非常強(qiáng)大。往往我們在工作中需要經(jīng)常使用 Excel 來從表格生成曲線圖,但步驟往往比較繁瑣,而用 Python 則可以輕松實(shí)現(xiàn)。

        1. 從 csv 或 excel 提取數(shù)據(jù)來畫圖

        本節(jié)需要先安裝 pandas 、matplotlib、seaborn

        pip install pandas matplotlib seaborn

        我們以剛才創(chuàng)建的 tips_2.xlsx 這個 excel 為例,來介紹我們?nèi)绾伟?Excel 表格中的數(shù)據(jù)畫成圖。

        tips_2.xlsx 是上一篇我們生成的:Python 萬能代碼模版:爬蟲代碼篇

        我們這次將 excel 中的賣出價一列,生成柱狀圖。

        代碼如下所示:

        # -*- coding: utf-8 -*-
        # @Author: AI悅創(chuàng)
        # @Date: 2021-09-14 21:56:37
        # @Last Modified by: aiyc
        # @Last Modified time: 2021-09-15 14:27:22
        import pandas as pd
        import matplotlib.pyplot as plt
        import seaborn as sns
        import numpy as np

        # 使用 pandas 讀取 excel, csv 文件的話換成 pd.read_csv 即可
        df = pd.read_excel("tips2.xlsx")

        # 因?yàn)榈谝恍惺侵形谋眍^,所以我們先過濾掉
        df = df[df.index>0]
        sns.set()
        figure2 = plt.figure(figsize = (10, 5))
        figure2.add_subplot(1,1,1)

        # 設(shè)置軸的屬性
        plt.xlabel("",fontsize = 14)
        plt.ylabel("賣出價", fontsize = 14)
        plt.xticks(fontsize=14)
        plt.yticks(fontsize=14)
        plt.title("外匯情況", fontsize=14)

        # 設(shè)置字體的屬性
        # plt.rcParams["font.sans-serif"] = ["Arial Unicode MS"]
        # plt.rcParams["font.family"] = 'sans-serif'
        plt.rcParams["font.sans-serif"] = "SimHei"
        plt.rcParams["axes.unicode_minus"] = False

        category = df[0]
        index_category = np.arange(len(category))

        # 將賣出價 轉(zhuǎn)換為數(shù)字
        df[3] = pd.to_numeric(df[3])
        plt.xticks(rotation = 90)
        plt.bar(x=df[0], height=df[3].values, color=[1,0,1])
        plt.show()

        輸出如下所示:

        替換說明:

        1. 替換要畫圖的 excel 文件夾名稱

        2. Y 軸的標(biāo)題

        3. 圖的標(biāo)題

        4. 橫軸的數(shù)據(jù)(第幾列做橫軸)

        5. 縱軸的數(shù)據(jù)(第幾列做縱軸)

        代碼: https://github.com/AndersonHJB/AIYC_DATA/tree/main/02-玩轉(zhuǎn)圖表,實(shí)現(xiàn)數(shù)據(jù)可視化/2.1%20從%20csv%20或%20excel%20提取數(shù)據(jù)來畫圖

        2. 從文本文件中生成詞云

        需要先安裝 wordcloud,jieba

        pip install wordcloud jieba

        詞云是最近數(shù)據(jù)分析報告中非常常見的數(shù)據(jù)表現(xiàn)形式了,它會從一段文字中抽取出高頻的詞匯并且以圖片的形式將它們展示出來。

        如何用 Python 生成詞云呢?

        為了做示范,我們首先解析第一步我們抓取的 tips_1.html 網(wǎng)頁(考研網(wǎng)),將所有的新聞標(biāo)題都存儲到一個文本文檔中。

        代碼如下:

        # -*- coding: utf-8 -*-
        # @Author: AI悅創(chuàng)
        # @Date: 2021-09-15 22:15:30
        # @Last Modified by: aiyc
        # @Last Modified time: 2021-09-15 23:12:34
        from bs4 import BeautifulSoup

        # 輸入?yún)?shù)為要分析的 html 文件名,返回值為對應(yīng)的 BeautifulSoup 對象
        def create_doc_from_filename(filename):
        with open(filename, "r", encoding='utf-8')as f:
        html_content = f.read()
        doc = BeautifulSoup(html_content, "lxml")
        return doc


        def parse(doc):
        post_list = doc.find_all("div",class_="post-info")
        result = []
        for post in post_list:
        link = post.find_all("a")[1]
        result.append(link.text.strip())

        result_str="\n".join(result)
        with open("news_title.txt", "w", encoding='utf-8') as fo:
        fo.write(result_str)

        def main():
        filename = "tips1.html"
        doc = create_doc_from_filename(filename)
        parse(doc)

        if __name__ == '__main__':
        main()

        接下來我們將 news_title.txt 這個文本文件中的漢字進(jìn)行分詞,并生成詞云。代碼如下:

        import jieba
        import wordcloud
        import matplotlib.pyplot as plt

        def create_ciyun():
        text = ""
        with open ("news_title.txt", encoding="utf-8") as fo:
        text = fo.read()
        split_list = jieba.lcut(text)
        final_text = " ".join(split_list)

        stopwords= ["的", "是", "了"]
        # Windows 系統(tǒng)的 font_path 替換為'C:\Windows\Fonts\STZHONGS.ttf'
        wc = wordcloud.WordCloud(font_path = r"C:\Windows\Fonts\STZHONGS.TTF", width=1000, height=700, background_color="white",max_words=100,stopwords = stopwords)
        wc.generate(final_text)
        plt.imshow(wc)
        plt.axis("off")
        plt.show()

        然后,在 main 函數(shù)中調(diào)用:

        def main():
        filename = "tips1.html"
        doc = create_doc_from_filename(filename)
        parse(doc)
        create_ciyun()

        為了方便閱讀,這里我也把整合好的代碼放出來:

        # -*- coding: utf-8 -*-
        # @Author: AI悅創(chuàng)
        # @Date: 2021-09-15 22:15:30
        # @Last Modified by: aiyc
        # @Last Modified time: 2021-09-15 23:21:44
        import jieba
        import wordcloud
        import matplotlib.pyplot as plt
        from bs4 import BeautifulSoup

        # 輸入?yún)?shù)為要分析的 html 文件名,返回值為對應(yīng)的 BeautifulSoup 對象
        def create_doc_from_filename(filename):
        with open(filename, "r", encoding='utf-8')as f:
        html_content = f.read()
        doc = BeautifulSoup(html_content, "lxml")
        return doc


        def parse(doc):
        post_list = doc.find_all("div",class_="post-info")
        result = []
        for post in post_list:
        link = post.find_all("a")[1]
        result.append(link.text.strip())

        result_str="\n".join(result)
        with open("news_title.txt", "w", encoding='utf-8') as fo:
        fo.write(result_str)


        def create_ciyun():
        text = ""
        with open ("news_title.txt", encoding="utf-8") as fo:
        text = fo.read()
        split_list = jieba.lcut(text)
        final_text = " ".join(split_list)

        stopwords= ["的", "是", "了"]
        # Windows 系統(tǒng)的 font_path 替換為'C:\Windows\Fonts\STZHONGS.ttf'
        wc = wordcloud.WordCloud(font_path = r"C:\Windows\Fonts\STZHONGS.TTF", width=1000, height=700, background_color="white",max_words=100,stopwords = stopwords)
        wc.generate(final_text)
        plt.imshow(wc)
        plt.axis("off")
        plt.show()

        def main():
        filename = "tips1.html"
        doc = create_doc_from_filename(filename)
        parse(doc)
        create_ciyun()

        if __name__ == '__main__':
        main()

        不過還是建議閱讀源代碼文件,源代碼文件我此片段最后會放出來。

        輸出結(jié)果如下:

        如果你想生成自己的詞云,首先你需要想清楚你的數(shù)據(jù)來源,一般是一個網(wǎng)頁或者一個文本文件。

        • 如果是網(wǎng)頁的話可以首先保存到本地,提取文本,之后就可以進(jìn)行代碼替換來生成了。(對于網(wǎng)頁文件,需要自行提取文本咯,實(shí)在不會就把網(wǎng)頁的文件的內(nèi)容,復(fù)制出來。保存成 .txt 格式文件。
        • 如果是文本,直接復(fù)制在 text,再執(zhí)行下文即可。)

        我們代碼模板,實(shí)際是下面這個模板:

        def create_ciyun():
        text = ""
        with open ("news_title.txt", encoding="utf-8") as fo:
        text = fo.read()
        split_list = jieba.lcut(text)
        final_text = " ".join(split_list)

        stopwords= ["的", "是", "了"]
        # Windows 系統(tǒng)的 font_path 替換為'C:\Windows\Fonts\STZHONGS.ttf'
        wc = wordcloud.WordCloud(font_path = r"C:\Windows\Fonts\STZHONGS.TTF", width=1000, height=700, background_color="white",max_words=100,stopwords = stopwords)
        wc.generate(final_text)
        plt.imshow(wc)
        plt.axis("off")
        plt.show()

        替換說明:

        1. 替換為你準(zhǔn)備的網(wǎng)頁或者文本文件的文件名。

        PS:上面的模板生成的詞語適合非專業(yè)的使用,畢竟如果要較真的話,還是很糙的。

        代碼:https://github.com/AndersonHJB/AIYC_DATA/tree/main/02-玩轉(zhuǎn)圖表,實(shí)現(xiàn)數(shù)據(jù)可視化/2.2%20從文本文件中生成詞云

        AI悅創(chuàng)·推出輔導(dǎo)班啦,包括「Python 語言輔導(dǎo)班、C++輔導(dǎo)班、算法/數(shù)據(jù)結(jié)構(gòu)輔導(dǎo)班、少兒編程、pygame 游戲開發(fā)」,全部都是一對一教學(xué):一對一輔導(dǎo) + 一對一答疑 + 布置作業(yè) + 項(xiàng)目實(shí)踐等。QQ、微信在線,隨時響應(yīng)!V:Jiabcdefh

        作者:AI悅創(chuàng)
        排版:AI悅創(chuàng)





        黃家寶丨AI悅創(chuàng)

        隱形字

        攝影公眾號「悅創(chuàng)攝影研習(xí)社」


        在這里分享自己的一些經(jīng)驗(yàn)、想法和見解。


        長按識別二維碼關(guān)注




        好文和朋友一起看~

        瀏覽 142
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            成人视频在线观看网址 | 5566中文字幕 | a黄色一级片 | 嫩嫩的一线天XXX馒头 | av高清| av水果派 | 亚洲男人天堂网 | 青娱乐免费 | 视频一区在线播放 | 日本男吃奶玩乳30分钟 |