欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)詞云圖詞頻統(tǒng)計

 更新時間:2022年12月26日 14:47:45   作者:顧城沐心  
這篇文章主要為大家詳細(xì)介紹了Python數(shù)據(jù)分析中的詞頻統(tǒng)計和詞云圖可視化,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定的幫助,需要的可以參考一下

一:安裝必要的庫

導(dǎo)入必要的庫

import collections  # 詞頻統(tǒng)計庫
import os
import re  # 正則表達式庫
import urllib.error  # 指定url,獲取網(wǎng)頁數(shù)據(jù)
import urllib.request
import jieba  # 結(jié)巴分詞
import matplotlib.pyplot as plt  # 圖像展示庫
import numpy as np  # numpy數(shù)據(jù)處理庫
import pandas as pd
import wordcloud  # 詞云展示庫
import xlwt  # 進行excel操作
from PIL import Image  # 圖像處理庫
from bs4 import BeautifulSoup  # 網(wǎng)頁解析,獲取數(shù)據(jù)
from pyecharts.charts import Bar  # 畫柱形圖

導(dǎo)入的庫,如果出現(xiàn)報錯,自己安裝即可 

如下安裝示例1

pip install xlrd  -i https://pypi.tuna.tsinghua.edu.cn/simple

如下安裝示例2

詞云庫下載,需要注意查看自己版本,下載對應(yīng)版本安裝

https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 

如博主使用的是python3.7,64位,【可以調(diào)出cmd 輸入python回車即可查看】  

總之,安裝必要的庫,比較簡單,這邊不過多闡述 

二:數(shù)據(jù)分析 條形圖可視化

電影評分前25名,條形圖展示

    # 可視化
    data = pd.read_excel('豆瓣電影Top250.xls')
    df = data.sort_values('評分', ascending=False).head(25)
    v = df['影片中文名'].values.tolist()  # tolist()將數(shù)據(jù)轉(zhuǎn)換為列表形式
    d = df['評分'].values.tolist()
    # 設(shè)置顏色
    color_series = ['#2C6BA0', '#2B55A1', '#2D3D8E', '#44388E', '#6A368B'
                                                                '#7D3990', '#A63F98', '#C31C88', '#D52178', '#D5225B']
    print("-----" * 15)
    bar = (
        Bar()
            .add_xaxis([i for i in df['影片中文名'].values.tolist()])
            .add_yaxis('評分前25名', df['評價數(shù)'].values.tolist())
    )
    bar.render("./條形圖.html")
    print("柱形圖保存成功!")

生成html網(wǎng)頁可以查看條形圖 電影評分前25名

三:數(shù)據(jù)分析 詞頻統(tǒng)計 詞云圖可視化

# 讀取文件
fn = open('top250.txt', 'r', encoding='utf-8')
string_data = fn.read()
fn.close()

需要特別注意的是,文件格式為utf8,可對txt另存為,再設(shè)置編碼格式,如下

詞頻統(tǒng)計 詞云圖生成 :

    # 讀取文件
    fn = open('top250.txt', 'r', encoding='utf-8')
    string_data = fn.read()
    fn.close()
    # 文本預(yù)處理
    pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定義正則表達式匹配模式
    string_data = re.sub(pattern, '', string_data)  # 將符合模式的字符去除
    # 文本分詞
    seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精確模式分詞
    object_list = []
    remove_words = [u'19', u',', u'20', u'德國', u'導(dǎo)演', u'日本', u'法國', u'等', u'能', u'都', u'。', u' ', u'、', u'中', u'在',
                    u'了',
                    u'20', u'大陸', u'我們', u'美國']  # 自定義去除詞庫
 
    for word in seg_list_exact:  # 循環(huán)讀出每個分詞
        if word not in remove_words:  # 如果不在去除詞庫中
            object_list.append(word)  # 分詞追加到列表
 
    # 詞頻統(tǒng)計
    word_counts = collections.Counter(object_list)
    word_counts_top10 = word_counts.most_common(10)
    print(word_counts_top10)  # 輸出檢查
    word_counts_top10 = str(word_counts_top10)
 
    # 詞頻展示
    mask = np.array(Image.open('image.jpg'))
    wc = wordcloud.WordCloud(
        font_path='simfang.ttf',
        mask=mask,
        max_words=100,  # 最多顯示詞數(shù)
        max_font_size=150,  # 字體最大值
        background_color='white',
        width=800, height=600,
    )
 
    wc.generate_from_frequencies(word_counts)
    plt.imshow(wc)
    plt.axis('off')
    plt.show()
    wc.to_file('wordcloud.png')

運行測試,實現(xiàn)詞頻統(tǒng)計 

同時生成詞云圖 保存本地可查看 

完整源碼分享,需要自取

import collections  # 詞頻統(tǒng)計庫
import os
import re  # 正則表達式庫
import urllib.error  # 指定url,獲取網(wǎng)頁數(shù)據(jù)
import urllib.request
import jieba  # 結(jié)巴分詞
import matplotlib.pyplot as plt  # 圖像展示庫
import numpy as np  # numpy數(shù)據(jù)處理庫
import pandas as pd
import wordcloud  # 詞云展示庫
import xlwt  # 進行excel操作
from PIL import Image  # 圖像處理庫
from bs4 import BeautifulSoup  # 網(wǎng)頁解析,獲取數(shù)據(jù)
from pyecharts.charts import Bar  # 畫柱形圖
 
 
def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 獲取網(wǎng)頁
    datalist = getDate(baseurl)
    savepath = ".\\豆瓣電影Top250.xls"
    # 保存數(shù)據(jù)
    saveData(datalist, savepath)
 
 
head = {
    "User-Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 85.0.4183.121Safari / 537.36"
}
 
# 影片詳情鏈接規(guī)則
findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" >')  # 創(chuàng)建正則表達式對象
# 影片圖片的鏈接
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
# 影片片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 影片評分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 評價人數(shù)
findJudge = re.compile(r'<span>(\d*)人評價</span>')
# 概況
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 找到影片的相關(guān)內(nèi)容
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
 
 
# 爬取網(wǎng)頁
def getDate(baseurl):
    datalist = []
    x = 1
    # 調(diào)用獲取頁面信息的函數(shù)(10次)
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        html = askURL(url)  # 保存獲取到的網(wǎng)頁源碼
        # 逐一解析數(shù)據(jù)
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div', class_="item"):
            data = []  # 保存一部電影的所有信息
            item = str(item)  # 將item轉(zhuǎn)換為字符串
            # 影片詳情鏈接
            link = re.findall(findLink, item)[0]
            # 追加內(nèi)容到列表
            data.append(link)
 
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)
 
            titles = re.findall(findTitle, item)
            if (len(titles) == 2):
                ctitle = titles[0]
                data.append(ctitle)  # 添加中文名
                otitle = titles[1].replace("/", "")
                data.append(otitle)  # 添加外國名
            else:
                data.append(titles[0])
                data.append(' ')  # 外國名如果沒有則留空
 
            rating = re.findall(findRating, item)[0]
            data.append(rating)
 
            judgeNum = re.findall(findJudge, item)[0]
            data.append(judgeNum)
 
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")
                data.append(inq)
            else:
                data.append(' ')
 
            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd)
            bd = re.sub('/', " ", bd)
            data.append(bd.strip())
 
            datalist.append(data)  # 把處理好的一部電影信息放入datalist
            # print(link)
 
            # 下載圖片到本地
            root = "D://moviePic//"
            path = root + str(x) + '.jpg'
            try:
                if not os.path.exists(root):
                    os.mkdir(root)
                if not os.path.exists(path):
                    # r = requests.get(imgSrc, headers=head)
                    urllib.request.urlretrieve(imgSrc, path)
                    # with open(path, 'wb') as f:
                    #   f.write(r.content)
                    #   f.close()
                    print("下載第%d部電影封面" % (x))
                    x += 1
                else:
                    print("文件保存成功")
            except:
                print("下載失敗")
    return datalist
 
 
# 得到指定一個url的網(wǎng)頁內(nèi)容
def askURL(url):
    request = urllib.request.Request(url, headers=head)
    html = ""
    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
 
 
# 保存數(shù)據(jù)
def saveData(datalist, savepath):
    book = xlwt.Workbook(encoding="utf-8", style_compression=0)  # 創(chuàng)建workbook對象
    sheet = book.add_sheet("豆瓣電影Top250", cell_overwrite_ok=True)  # 創(chuàng)建工作表
    col = ('電影詳情鏈接', "圖片鏈接", "影片中文名", "影片外國名", "評分", "評價數(shù)", "概況", "相關(guān)信息")
    try:
        for i in range(0, 8):
            sheet.write(0, i, col[i])  # 輸入列名
        for i in range(0, 250):
            print("第%d條" % (i + 1))
            data = datalist[i]
            for j in range(0, 8):
                sheet.write(i + 1, j, data[j])
        book.save(savepath)
    except:
        print("爬取異常")
 
 
if __name__ == '__main__':
    main()
    print("爬取完畢")
    # 可視化
    data = pd.read_excel('豆瓣電影Top250.xls')
    df = data.sort_values('評分', ascending=False).head(25)
    v = df['影片中文名'].values.tolist()  # tolist()將數(shù)據(jù)轉(zhuǎn)換為列表形式
    d = df['評分'].values.tolist()
    # 設(shè)置顏色
    color_series = ['#2C6BA0', '#2B55A1', '#2D3D8E', '#44388E', '#6A368B'
                                                                '#7D3990', '#A63F98', '#C31C88', '#D52178', '#D5225B']
    print("-----" * 15)
    bar = (
        Bar()
            .add_xaxis([i for i in df['影片中文名'].values.tolist()])
            .add_yaxis('評分前25名', df['評價數(shù)'].values.tolist())
    )
    bar.render("./條形圖.html")
    print("柱形圖保存成功!")
    # 讀取文件
    fn = open('top250.txt', 'r', encoding='utf-8')
    string_data = fn.read()
    fn.close()
    # 文本預(yù)處理
    pattern = re.compile(u'\t|\n|\.|-|:|;|\)|\(|\?|"')  # 定義正則表達式匹配模式
    string_data = re.sub(pattern, '', string_data)  # 將符合模式的字符去除
    # 文本分詞
    seg_list_exact = jieba.cut(string_data, cut_all=False)  # 精確模式分詞
    object_list = []
    remove_words = [u'19', u',', u'20', u'德國', u'導(dǎo)演', u'日本', u'法國', u'等', u'能', u'都', u'。', u' ', u'、', u'中', u'在',
                    u'了',
                    u'20', u'大陸', u'我們', u'美國']  # 自定義去除詞庫
 
    for word in seg_list_exact:  # 循環(huán)讀出每個分詞
        if word not in remove_words:  # 如果不在去除詞庫中
            object_list.append(word)  # 分詞追加到列表
 
    # 詞頻統(tǒng)計
    word_counts = collections.Counter(object_list)
    word_counts_top10 = word_counts.most_common(10)
    print(word_counts_top10)  # 輸出檢查
    word_counts_top10 = str(word_counts_top10)
 
    # 詞頻展示
    mask = np.array(Image.open('image.jpg'))
    wc = wordcloud.WordCloud(
        font_path='simfang.ttf',
        mask=mask,
        max_words=100,  # 最多顯示詞數(shù)
        max_font_size=150,  # 字體最大值
        background_color='white',
        width=800, height=600,
    )
 
    wc.generate_from_frequencies(word_counts)
    plt.imshow(wc)
    plt.axis('off')
    plt.show()
    wc.to_file('wordcloud.png')

到此這篇關(guān)于Python實現(xiàn)詞云圖詞頻統(tǒng)計的文章就介紹到這了,更多相關(guān)Python詞云圖詞頻統(tǒng)計內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中Pytest常用的插件

    python中Pytest常用的插件

    這篇文章主要介紹了python中Pytest常用的插件,Pytest是Python的一種單元測試框架,與unittest相比,使用起來更簡潔、效率更高,也是目前大部分使用python編寫測試用例的小伙伴們的第一選擇了
    2022-06-06
  • 通過Python讀取照片的Exif信息解鎖圖片背后的故事

    通過Python讀取照片的Exif信息解鎖圖片背后的故事

    這篇文章主要為大家介紹了通過Python讀取照片的Exif信息解鎖圖片背后的故事探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-12-12
  • python執(zhí)行精確的小數(shù)計算方法

    python執(zhí)行精確的小數(shù)計算方法

    今天小編就為大家分享一篇python執(zhí)行精確的小數(shù)計算方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python的re模塊應(yīng)用實例

    python的re模塊應(yīng)用實例

    這篇文章主要介紹了python的re模塊應(yīng)用實例,包括了常見的正則匹配技巧,需要的朋友可以參考下
    2014-09-09
  • Django框架中模型的用法

    Django框架中模型的用法

    這篇文章介紹了Django框架中模型的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • python批量處理文件或文件夾

    python批量處理文件或文件夾

    這篇文章主要為大家詳細(xì)介紹了python批量處理文件或文件夾,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • 基于Python編寫微信清理工具的示例代碼

    基于Python編寫微信清理工具的示例代碼

    這篇文章主要和大家分享一個用Python語言編寫的微信清理小工具的示例代碼,而且該工具不會刪除文字的聊天記錄,感興趣的可以了解一下
    2022-05-05
  • Python?pyinstaller打包exe最新完整圖文教程

    Python?pyinstaller打包exe最新完整圖文教程

    pyinstaller是一個非常簡單的打包python的py文件的庫,下面這篇文章主要給大家介紹了關(guān)于Python?pyinstaller打包exe的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12
  • Keras保存模型并載入模型繼續(xù)訓(xùn)練的實現(xiàn)

    Keras保存模型并載入模型繼續(xù)訓(xùn)練的實現(xiàn)

    這篇文章主要介紹了Keras保存模型并載入模型繼續(xù)訓(xùn)練的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • python中幾種括號的使用()、[]、{}舉例說明

    python中幾種括號的使用()、[]、{}舉例說明

    這篇文章主要介紹了python中幾種括號的使用()、[]、{}舉例說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05

最新評論