網(wǎng)站首頁 編程語言 正文
python共現(xiàn)矩陣實現(xiàn)
最近在學習python詞庫的可視化,其中有一個依據(jù)共現(xiàn)矩陣制作的可視化,感覺十分炫酷,便以此復刻。
項目背景
本人利用爬蟲獲取各大博客網(wǎng)站的文章,在進行jieba分詞,得到每篇文章的關鍵詞,對這些關鍵詞進行共現(xiàn)矩陣的可視化。
什么是共現(xiàn)矩陣
比如我們有兩句話:
ls = ['我永遠喜歡三上悠亞', '三上悠亞又出新作了']
在jieba分詞下我們可以得到如下效果:
我們就可以構建一個以關鍵詞的共現(xiàn)矩陣:
['', '我', '永遠', '喜歡', '三上', '悠亞', '又', '出', '新作', '了']
['我', 0, 1, 1, 1, 1, 0, 0, 0, 0]
['永遠', 1, 0, 1, 1, 1, 0, 0, 0, 0]
['喜歡' 1, 1, 0, 1, 1, 0, 0, 0, 0]
['三上', 1, 1, 1, 0, 1, 1, 1, 1, 1]
['悠亞', 1, 1, 1, 1, 0, 1, 1, 1, 1]
['又', 0, 0, 0, 1, 1, 0, 1, 1, 1]
['出', 0, 0, 0, 1, 1, 1, 0, 1, 1]
['新作', 0, 0, 0, 1, 1, 1, 1, 0, 1]
['了', 0, 0, 0, 1, 1, 1, 1, 1, 0]]
解釋一下,“我永遠喜歡三上悠亞”,這一句話中,“我”和“永遠”共同出現(xiàn)了一次,在共現(xiàn)矩陣對應的[ i ] [ j ]和[ j ][ i ]上+1,并依次類推。
基于這個原因,我們可以發(fā)現(xiàn),共現(xiàn)矩陣的特點是:
- 共現(xiàn)矩陣的[0][0]為空。
- 共現(xiàn)矩陣的第一行第一列是關鍵詞。
- 對角線全為0。
- 共現(xiàn)矩陣其實是一個對稱矩陣。
當然,在實際的操作中,這些關鍵詞是需要經(jīng)過清洗的,這樣的可視化才干凈。
共現(xiàn)矩陣的構建思路
- 每篇文章關鍵詞的二維數(shù)組data_array。
- 所有關鍵詞的集合set_word。
- 建立關鍵詞長度+1的矩陣matrix。
- 賦值矩陣的第一行與第一列為關鍵詞。
- 設置矩陣對角線為0。
- 遍歷formated_data,讓取出的行關鍵詞和取出的列關鍵詞進行組合,共現(xiàn)則+1。
共現(xiàn)矩陣的代碼實現(xiàn)
# coding:utf-8
import numpy as np
import pandas as pd
import jieba.analyse
import os
# 獲取關鍵詞
def Get_file_keywords(dir):
data_array = [] # 每篇文章關鍵詞的二維數(shù)組
set_word = [] # 所有關鍵詞的集合
try:
fo = open('dic_test.txt', 'w+', encoding='UTF-8')
# keywords = fo.read()
for home, dirs, files in os.walk(dir): # 遍歷文件夾下的每篇文章
for filename in files:
fullname = os.path.join(home, filename)
f = open(fullname, 'r', encoding='UTF-8')
sentence = f.read()
words = " ".join(jieba.analyse.extract_tags(sentence=sentence, topK=30, withWeight=False,
allowPOS=('n'))) # TF-IDF分詞
words = words.split(' ')
data_array.append(words)
for word in words:
if word not in set_word:
set_word.append(word)
set_word = list(set(set_word)) # 所有關鍵詞的集合
return data_array, set_word
except Exception as reason:
print('出現(xiàn)錯誤:', reason)
return data_array, set_word
# 初始化矩陣
def build_matirx(set_word):
edge = len(set_word) + 1 # 建立矩陣,矩陣的高度和寬度為關鍵詞集合的長度+1
'''matrix = np.zeros((edge, edge), dtype=str)''' # 另一種初始化方法
matrix = [['' for j in range(edge)] for i in range(edge)] # 初始化矩陣
matrix[0][1:] = np.array(set_word)
matrix = list(map(list, zip(*matrix)))
matrix[0][1:] = np.array(set_word) # 賦值矩陣的第一行與第一列
return matrix
# 計算各個關鍵詞的共現(xiàn)次數(shù)
def count_matrix(matrix, formated_data):
for row in range(1, len(matrix)):
# 遍歷矩陣第一行,跳過下標為0的元素
for col in range(1, len(matrix)):
# 遍歷矩陣第一列,跳過下標為0的元素
# 實際上就是為了跳過matrix中下標為[0][0]的元素,因為[0][0]為空,不為關鍵詞
if matrix[0][row] == matrix[col][0]:
# 如果取出的行關鍵詞和取出的列關鍵詞相同,則其對應的共現(xiàn)次數(shù)為0,即矩陣對角線為0
matrix[col][row] = str(0)
else:
counter = 0 # 初始化計數(shù)器
for ech in formated_data:
# 遍歷格式化后的原始數(shù)據(jù),讓取出的行關鍵詞和取出的列關鍵詞進行組合,
# 再放到每條原始數(shù)據(jù)中查詢
if matrix[0][row] in ech and matrix[col][0] in ech:
counter += 1
else:
continue
matrix[col][row] = str(counter)
return matrix
def main():
formated_data, set_word = Get_file_keywords(r'D:\untitled\test')
print(set_word)
print(formated_data)
matrix = build_matirx(set_word)
matrix = count_matrix(matrix, formated_data)
data1 = pd.DataFrame(matrix)
data1.to_csv('data.csv', index=0, columns=None, encoding='utf_8_sig')
main()
共現(xiàn)矩陣(共詞矩陣)計算
共現(xiàn)矩陣(共詞矩陣)
統(tǒng)計文本中兩兩詞組之間共同出現(xiàn)的次數(shù),以此來描述詞組間的親密度
code(我這里求的對角線元素為該字段在文本中出現(xiàn)的總次數(shù)):
import pandas as pd
def gx_matrix(vol_li):
# 整合一下,輸入是df列,輸出直接是矩陣
names = locals()
all_col0 = [] # 用來后續(xù)求所有字段的集合
for row in vol_li:
all_col0 += row
for each in row: # 對每行的元素進行處理,存在該字段字典的話,再進行后續(xù)判斷,否則創(chuàng)造該字段字典
try:
for each1 in row: # 對已存在字典,循環(huán)該行每個元素,存在則在已有次數(shù)上加一,第一次出現(xiàn)創(chuàng)建鍵值對“字段:1”
try:
names['dic_' + each][each1] = names['dic_' + each][each1] + 1 # 嘗試,一起出現(xiàn)過的話,直接加1
except:
names['dic_' + each][each1] = 1 # 沒有的話,第一次加1
except:
names['dic_' + each] = dict.fromkeys(row, 1) # 字段首次出現(xiàn),創(chuàng)造字典
# 根據(jù)生成的計數(shù)字典生成矩陣
all_col = list(set(all_col0)) # 所有的字段(所有動物的集合)
all_col.sort(reverse=False) # 給定詞匯列表排序排序,為了和生成空矩陣的橫向列名一致
df_final0 = pd.DataFrame(columns=all_col) # 生成空矩陣
for each in all_col: # 空矩陣中每列,存在給字段字典,轉為一列存入矩陣,否則先創(chuàng)造全為零的字典,再填充進矩陣
try:
temp = pd.DataFrame(names['dic_' + each], index=[each])
except:
names['dic_' + each] = dict.fromkeys(all_col, 0)
temp = pd.DataFrame(names['dic_' + each], index=[each])
df_final0 = pd.concat([df_final0, temp]) # 拼接
df_final = df_final0.fillna(0)
return df_final
if __name__ == '__main__':
temp1 = ['狗', '獅子', '孔雀', '豬']
temp2 = ['大象', '獅子', '老虎', '豬']
temp3 = ['大象', '北極熊', '老虎', '豬']
temp4 = ['大象', '狗', '老虎', '小雞']
temp5 = ['狐貍', '獅子', '老虎', '豬']
temp_all = [temp2, temp1, temp3, temp4, temp5]
vol_li = pd.Series(temp_all)
df_matrix = gx_matrix(vol_li)
print(df_matrix)
輸入是整成這個樣子的series
求出每個字段與各字段的出現(xiàn)次數(shù)的字典
最后轉為df
補充一點
這里如果用大象所在列,除以大象出現(xiàn)的次數(shù),比值高的,表明兩者一起出現(xiàn)的次數(shù)多,如果這列比值中,有兩個元素a和b的比值均大于0.8(也不一定是0.8啦),就是均比較高,則說明a和b和大象三個一起出現(xiàn)的次數(shù)多!!!
即可以求出文本中經(jīng)常一起出現(xiàn)的詞組搭配,比如這里的第二列,大象一共出現(xiàn)3次,與老虎出現(xiàn)3次,與豬出現(xiàn)2次,則可以推導出大象,老虎,豬一起出現(xiàn)的概率較高。
也可以把出現(xiàn)總次數(shù)拎出來,放在最后一列,則代碼為:
# 計算每個字段的出現(xiàn)次數(shù),并列為最后一行
df_final['all_times'] = ''
for each in df_final0.columns:
df_final['all_times'].loc[each] = df_final0.loc[each, each]
放在上述代碼df_final = df_final0.fillna(0)的后面即可
結果為
我第一次放代碼上來的時候中間有一塊縮進錯了,感謝提出問題的同學的提醒,現(xiàn)在是更正過的代碼!!!
原文鏈接:https://blog.csdn.net/qq_43650934/article/details/104329469
相關推薦
- 2022-07-29 Python列表append()函數(shù)使用方法詳解_python
- 2022-04-16 python代碼有一行標黃問題的解決方案_python
- 2022-12-08 C語言如何實現(xiàn)成績等級判別_C 語言
- 2023-01-03 python案例中Flask全局配置示例詳解_python
- 2021-12-02 docker容器時區(qū)錯誤問題_docker
- 2022-04-07 C++?string與int的相互轉換(使用C++11)_C 語言
- 2022-05-15 python自動化測試之Selenium詳解_python
- 2022-06-19 Go獲取兩個時間點時間差的具體實現(xiàn)_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支