您現在的位置是:首頁 > 運動

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

由 悅文天下 發表于 運動2022-08-03
簡介txt’, ‘r’, encoding=‘utf-8’)outputs = open(‘職位表述文字分詞後_outputs

雲可以組成什麼詞語

「來源: |Python爬蟲與資料探勘 ID:crawler_python」

回覆“

書籍

”即可獲贈Python從入門到進階共10本電子書

蒼蒼竹林寺,杳杳鐘聲晚。

大家好,我是Python進階者。

前言

前幾天星耀群有個叫【小明】的粉絲在問了一道關於Python處理文字視覺化+語義分析的問題,如下圖所示。

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

他要構建語料庫,目前透過Python網路爬蟲抓到的資料存在一個csv檔案裡邊,現在要把資料放進txt裡,表示不會,然後還有後面的詞雲視覺化,分詞,語義分析等,都不太會。

關於詞雲的文章,歷史文章已經寫了十幾篇了,感興趣的話可以在公眾號歷史文章搜尋關鍵字“詞雲”前往,但是關於分詞和語義分析的文章,就分享過一篇,這個我在讀研的時候寫的,雖然有些時日,但是內容依舊精彩,歡迎前往查探:Python大佬分析了15萬歌詞,告訴你民謠歌手們到底在唱什麼。

一、思路

內容稍微有點多,大體思路如下,先將csv中的文字取出,之後使用停用詞做分詞處理,再做詞雲圖,之後做情感分析。

1、將csv檔案中的文字逐行取出,存新的txt檔案,這裡執行程式碼《讀取csv檔案中文字並存txt文件。py》進行實現,得到檔案《職位表述文字。txt》

2、執行程式碼《使用停用詞獲取最後的文字內容。py》,得到使用停用詞獲取最後的文字內容,生成檔案《職位表述文字分詞後_outputs。txt》

3、執行程式碼《指定txt詞雲圖。py》,可以得到詞雲圖;

4、執行程式碼《jieba分詞並統計詞頻後輸出結果到Excel和txt文件。py》,得到《wordCount_all_lyrics。xls》和《分詞結果。txt》檔案,將《分詞結果。txt》中的統計值可以去除,生成《情感分析用詞。txt》,給第五步情感分析做準備

5、執行程式碼《情感分析。py》,得到情感分析的統計值,取平均值可以大致確認情感是正還是負。

關於本文的原始碼和資料我都已經打包好上傳到git了,在公眾號後臺回覆關鍵詞小明的資料即可獲取。

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

二、實現過程

1。將csv檔案中的文字逐行取出,存新的txt檔案

這裡執行程式碼《讀取csv檔案中文字並存txt文件。py》進行實現,得到檔案《職位表述文字。txt》,程式碼如下。

# coding: utf-8

import pandas as pd

df = pd。read_csv(‘。/職位描述。csv’, encoding=‘gbk’)

# print(df。head())

for text in df[‘Job_Description’]:

# print(text)

if text is not None:

with open(‘職位表述文字。txt’, mode=‘a’, encoding=‘utf-8’) as file:

file。write(str(text))

print(‘寫入完成’)

2。使用停用詞獲取最後的文字內容

執行程式碼《使用停用詞獲取最後的文字內容。py》,得到使用停用詞獲取最後的文字內容,生成檔案《職位表述文字分詞後_outputs。txt》,程式碼如下:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import jieba

# jieba。load_userdict(‘userdict。txt’)

# 建立停用詞list

def stopwordslist(filepath):

stopwords = [line。strip() for line in open(filepath, ‘r’, encoding=‘utf-8’)。readlines()]

return stopwords

# 對句子進行分詞

def seg_sentence(sentence):

sentence_seged = jieba。cut(sentence。strip())

stopwords = stopwordslist(‘stop_word。txt’) # 這裡載入停用詞的路徑

outstr = ‘’

for word in sentence_seged:

if word not in stopwords:

if word != ‘\t’:

outstr += word

outstr += “ ”

return outstr

inputs = open(‘職位表述文字。txt’, ‘r’, encoding=‘utf-8’)

outputs = open(‘職位表述文字分詞後_outputs。txt’, ‘w’, encoding=‘utf-8’)

for line in inputs:

line_seg = seg_sentence(line) # 這裡的返回值是字串

outputs。write(line_seg + ‘\n’)

outputs。close()

inputs。close()

關鍵節點,都有相應的註釋,你只需要替換對應的txt檔案即可,如果有遇到編碼問題,將utf-8改為gbk即可解決。

3。製作詞雲圖

執行程式碼《指定txt詞雲圖。py》,可以得到詞雲圖,程式碼如下:

from wordcloud import WordCloud

import jieba

import numpy

import PIL。Image as Image

def cut(text):

wordlist_jieba=jieba。cut(text)

space_wordlist=“ ”。join(wordlist_jieba)

return space_wordlist

with open(r“C:\Users\pdcfi\Desktop\xiaoming\職位表述文字。txt” ,encoding=“utf-8”)as file:

text=file。read()

text=cut(text)

mask_pic=numpy。array(Image。open(r“C:\Users\pdcfi\Desktop\xiaoming\python。png”))

wordcloud = WordCloud(font_path=r“C:/Windows/Fonts/simfang。ttf”,

collocations=False,

max_words= 100,

min_font_size=10,

max_font_size=500,

mask=mask_pic)。generate(text)

image=wordcloud。to_image()

# image。show()

wordcloud。to_file(‘詞雲圖。png’) # 把詞雲儲存下來

如果想用你自己的圖片,只需要替換原始圖片即可。這裡使用Python底圖做演示,得到的效果如下:

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

4。分詞統計

執行程式碼《jieba分詞並統計詞頻後輸出結果到Excel和txt文件。py》,得到《wordCount_all_lyrics。xls》和《分詞結果。txt》檔案,將《分詞結果。txt》中的統計值可以去除,生成《情感分析用詞。txt》,給第五步情感分析做準備,程式碼如下:

#!/usr/bin/env python3

# -*- coding:utf-8 -*-

import sys

import jieba

import jieba。analyse

import xlwt # 寫入Excel表的庫

# reload(sys)

# sys。setdefaultencoding(‘utf-8’)

if __name__ == “__main__”:

wbk = xlwt。Workbook(encoding=‘ascii’)

sheet = wbk。add_sheet(“wordCount”) # Excel單元格名字

word_lst = []

key_list = []

for line in open(‘職位表述文字。txt’, encoding=‘utf-8’): # 需要分詞統計的原始目標文件

item = line。strip(‘\n\r’)。split(‘\t’) # 製表格切分

# print item

tags = jieba。analyse。extract_tags(item[0]) # jieba分詞

for t in tags:

word_lst。append(t)

word_dict = {}

with open(“分詞結果。txt”, ‘w’) as wf2: # 指定生成檔案的名稱

for item in word_lst:

if item not in word_dict: # 統計數量

word_dict[item] = 1

else:

word_dict[item] += 1

orderList = list(word_dict。values())

orderList。sort(reverse=True)

# print orderList

for i in range(len(orderList)):

for key in word_dict:

if word_dict[key] == orderList[i]:

wf2。write(key + ‘ ’ + str(word_dict[key]) + ‘\n’) # 寫入txt文件

key_list。append(key)

word_dict[key] = 0

for i in range(len(key_list)):

sheet。write(i, 1, label=orderList[i])

sheet。write(i, 0, label=key_list[i])

wbk。save(‘wordCount_all_lyrics。xls’) # 儲存為 wordCount。xls檔案

得到的txt和excel檔案如下所示:

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

5。情感分析的統計值

執行程式碼《情感分析。py》,得到情感分析的統計值,取平均值可以大致確認情感是正還是負,程式碼如下:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

from snownlp import SnowNLP

# 積極/消極

# print(s。sentiments) # 0。9769551298267365 positive的機率

def get_word():

with open(“情感分析用詞。txt”, encoding=‘utf-8’) as f:

line = f。readline()

word_list = []

while line:

line = f。readline()

word_list。append(line。strip(‘\r\n’))

f。close()

return word_list

def get_sentiment(word):

text = u‘{}’。format(word)

s = SnowNLP(text)

print(s。sentiments)

if __name__ == ‘__main__’:

words = get_word()

for word in words:

get_sentiment(word)

# text = u‘’‘

# 也許

# ’‘’

# s = SnowNLP(text)

# print(s。sentiments)

# with open(‘lyric_sentiments。txt’, ‘a’, encoding=‘utf-8’) as fp:

# fp。write(str(s。sentiments)+‘\n’)

# print(‘happy end’)

基於NLP語義分析,程式執行之後,得到的情感得分值如下圖所示:

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

將得數取平均值,一般滿足0。5分以上,說明情感是積極的,這裡經過統計之後,發現整體是積極的。

四、總結

我是Python進階者。本文基於粉絲提問,針對一次文字處理,手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析,算是完成了一個小專案了。下次再遇到類似這種問題或者小的課堂作業,不妨拿本專案練練手,說不定有妙用噢,拿個高分不在話下!

最後感謝粉絲【小明】提問,感謝【(這是月亮的背面)】、【Python進階者】大佬解惑,感謝【冫馬訁成】大佬提供積極參與。

手把手教你對抓取的文字進行分詞、詞頻統計、詞雲視覺化和情感分析

推薦文章