python构建关键词共现矩阵
本文僅僅提供了實現思路,如果對算法速度有追求的請移步python構建關鍵詞共現矩陣速度優化(在此非常感謝這位同學的優化)
非常感謝南京大學的張同學發現我代碼中的bug,現文中的代碼均已經更新請放心使用,并且代碼放棄使用numpy進行矩陣的構建,因此可以對中文進行構建關鍵詞共現矩陣了。同時,有很多同學對我在blog中總是提到的“import自己的代碼“的代碼感興趣,現在已將代碼git至GITHUB中,需要的同學請自行clone,其中包括了filewalker.py(文件夾遍歷)、reader.py(txt、excel文件的讀寫操作)、buildfile.py(新建文件夾等),具體用法,請參考我的另一篇博文《import自己寫的.py》
這篇博文中為了方便矩陣構建和變換,我使用了numpy,但是numpy不支持讀取和寫入中文字符,僅僅支持英文(或者拉丁文?),因此希望做中文的關鍵詞共現實驗的同學,可以使用博文最下方的代碼,給大家造成不便,十分抱歉!
中科院的小伙伴Leo Wood已經用pandas實現了共現計算,傳送門:Python Pandas 構建共現矩陣
共現分析在數據分析中經常使用到,這里的關鍵詞可以指的是文獻中的關鍵詞、作者、作者機構等等。在其他領域中,如電影電視劇也可以用來研究演員共現矩陣等等。在得出共現矩陣后,可以使用UCINET、NETDRAW或者Gephi來進行共現圖譜的繪制,達到數據可視化的效果。
首先看看原始數據:
從圖中可以看出,a和b共現2次,和c共現2次,其余以此類推。
*下面的代碼中,存在import reader,reader是我自己寫的.py文件,以方便我每次讀取數據。這樣就不用每次讀取數據的時候都要再寫一遍with open了,具體怎么使用請看我另一篇博文python中import自己寫的.py
代碼如下:
為方便理解,我把每個函數返回的結果打印出來:
------------------------------------------------ 2017-04-05 15:30:48 get_set_key called Document:構建一個關鍵詞集合,用于作為共現矩陣的首行和首列 get_set_key returns: ['f', 'd', 'c', 'a', 'b'] ------------------------------------------------ 2017-04-05 15:30:48 format_data called Document:格式化需要計算的數據,將原始數據格式轉換成二維數組 format_data returns: [['a', 'b', 'c'], ['b', 'a', 'f'], ['a', 'd', 'c']] ------------------------------------------------ 2017-04-05 15:30:48 build_matirx called Document:建立矩陣,矩陣的高度和寬度為關鍵詞集合的長度+1 build_matirx returns: [['' '' '' '' '' '']['' '' '' '' '' '']['' '' '' '' '' '']['' '' '' '' '' '']['' '' '' '' '' '']['' '' '' '' '' '']] ------------------------------------------------ 2017-04-05 15:30:48 init_matrix called Document:初始化矩陣,將關鍵詞集合賦值給第一列和第二列 init_matrix returns: [['' 'f' 'd' 'c' 'a' 'b']['f' '' '' '' '' '']['d' '' '' '' '' '']['c' '' '' '' '' '']['a' '' '' '' '' '']['b' '' '' '' '' '']] ------------------------------------------------ 2017-04-05 15:30:48 count_matrix called Document:計算各個關鍵詞共現次數 count_matrix returns: [['' 'f' 'd' 'c' 'a' 'b']['f' '0' '0' '0' '1' '1']['d' '0' '0' '1' '1' '0']['c' '0' '1' '0' '2' '1']['a' '1' '1' '2' '0' '2']['b' '1' '0' '1' '2' '0']]***Repl Closed***輸出的結果為:
中文關鍵詞的共現矩陣實現:
import os import xlrd import re from pprint import pprint as ptdef readxls(path):xl = xlrd.open_workbook(path)sheet = xl.sheets()[0]data = []for i in range(0, sheet.ncols):data.append(list(sheet.col_values(i)))return (data[0])def wryer(path, text):with open(path, 'a', encoding='utf-8') as f:f.write(text)return path+' is ok!'def buildmatrix(x, y):return [[0 for j in range(y)] for i in range(x)]def dic(xlspath):keygroup = readxls(xlspath)keytxt = '/'.join(keygroup)keyfir = keytxt.split('/')keylist = list(set([key for key in keytxt.split('/') if key != '']))keydic = {}pos = 0for i in keylist:pos = pos+1keydic[pos] = str(i)return keydicdef showmatrix(matrix):matrixtxt = ''count = 0for i in range(0, len(matrix)):for j in range(0, len(matrix)):matrixtxt = matrixtxt+str(matrix[i][j])+'\t'matrixtxt = matrixtxt[:-1]+'\n'count = count+1print('No.'+str(count)+' had been done!')return matrixtxtdef inimatrix(matrix, dic, length):matrix[0][0] = '+'for i in range(1, length):matrix[0][i] = dic[i]for i in range(1, length):matrix[i][0] = dic[i]# pt(matrix)return matrixdef countmatirx(matrix, dic, mlength, keylis):for i in range(1, mlength):for j in range(1, mlength):count = 0for k in keylis:ech = str(k).split('/')# print(ech)if str(matrix[0][i]) in ech and str(matrix[j][0]) in ech and str(matrix[0][i]) != str(matrix[j][0]):count = count+1else:continuematrix[i][j] = str(count)return matrixdef main():xlspath = r'test.xlsx'wrypath = r'1.txt'keylis = (readxls(xlspath))keydic = dic(xlspath)length = len(keydic)+1matrix = buildmatrix(length, length)print('Matrix had been built successfully!')matrix = inimatrix(matrix, keydic, length)print('Col and row had been writen!')matrix = countmatirx(matrix, keydic, length, keylis)print('Matrix had been counted successfully!')matrixtxt = showmatrix(matrix)# pt(matrix)print(wryer(wrypath, matrixtxt))# print(keylis)if __name__ == '__main__':main()總結
以上是生活随笔為你收集整理的python构建关键词共现矩阵的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 学习《css世界》笔记之使用css实现凹
- 下一篇: 在IDEA中实现Python随机森林模型