NLP分析小说人物关系,找找主人公的真爱。
生活随笔
收集整理的這篇文章主要介紹了
NLP分析小说人物关系,找找主人公的真爱。
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
思路
基于共現(xiàn)來(lái)挖掘人物之間的關(guān)系。
準(zhǔn)備好三個(gè)存儲(chǔ)器
思路不解釋,自己看代碼,這也是我學(xué)習(xí)之后寫(xiě)的。
看別人文字思路,不如看代碼。畢竟文字思路多啦一道轉(zhuǎn)換。
步驟1
import jieba.posseg as pseg from tqdm import tqdm#設(shè)置一個(gè)進(jìn)度條 # 姓名字典 names = {} # 關(guān)系字典 relationships = {} # 每段內(nèi)人物關(guān)系 lineNames = [] #打開(kāi)文件 with open('射雕英雄傳.txt', 'r',encoding='utf-8') as fp:for line in tqdm(fp):line = line.strip('\n')#去除換行poss = pseg.cut(line)# 分詞返回詞性# 為新讀取的一段添加人物關(guān)系lineNames.append([])for w in poss:#遍歷每一個(gè)# print("%s:%s" % (w.word, w.flag))# 分詞長(zhǎng)度小于2 或詞性不為nr時(shí)則與影片所需分析人物無(wú)關(guān)if w.flag != "nr" or len(w.word) < 2:continuelineNames[-1].append(w.word)#當(dāng)前段存放人物名if names.get(w.word) is None:#如果姓名未出現(xiàn)過(guò)names[w.word] = 0#當(dāng)前姓名添加進(jìn)names字典里relationships[w.word] = {}#初始化該姓名關(guān)系圖# 人物出現(xiàn)次數(shù)+1names[w.word] += 1print('names\n',names) print('relationships\n',relationships) print('lineNames\n',lineNames)步驟2
#分析人物關(guān)系 for line in lineNames:for name1 in line:for name2 in line:if name1 == name2:continueif relationships[name1].get(name2) is None:# 兩個(gè)人物第一次共同出現(xiàn) 初始化次數(shù)relationships[name1][name2] = 1else:# 兩個(gè)人物共同出現(xiàn) 關(guān)系+1relationships[name1][name2] += 1步驟3
# 寫(xiě)csv文件 用于網(wǎng)絡(luò)圖使用 def generate_gephi():# 人物權(quán)重(節(jié)點(diǎn))with open("earth_node.csv", "w", encoding='utf-8') as f:f.write("Id Label Weight\r\n")for name, times in names.items():f.write(name + " " + name + " " + str(times) + "\r\n")# 人物關(guān)系邊(邊)with open("earth_edge.csv", "w", encoding='utf-8') as f:f.write("Source Target Weight\r\n")for name, edge in relationships.items():for v, w in edge.items():if w > 3:f.write(name + " " + v + " " + str(w) + "\r\n")generate_gephi()得到的數(shù)據(jù) 是一列的
需要應(yīng)用excel 技術(shù)將一列分成多列
如結(jié)果
畫(huà)圖
import pandas as pdfile1=pd.read_csv('earth_edge.csv',encoding='gbk')#人物關(guān)系 file1=file1.dropna()import networkx as nx from pylab import * import matplotlib.pyplot as plt mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = Falsedef painting(): #繪制人物親密度圖G = nx.Graph() # 繪制個(gè)人物之間的親密關(guān)系for index, row in file1.iterrows():G.add_node(row['Source'])#添加節(jié)點(diǎn)for index, row in file1.iterrows():G.add_weighted_edges_from([(row['Source'],row['Target'],row['Weight'])])pos = nx.shell_layout(G)print('畫(huà)出網(wǎng)絡(luò)圖像:')nx.draw(G, pos, with_labels=True, node_color='white', edge_color='red', node_size=400, alpha=0.5)plt.show()painting()人太多 ,圖炸啦。
接下來(lái)我只繪制重要人物的圖
import pandas as pd import numpy as np file=pd.read_csv('earth_node.csv',encoding='gbk')#人物權(quán)重文件 file=file.dropna()file1=pd.read_csv('earth_edge.csv',encoding='gbk')#人物關(guān)系文件 file1=file1.dropna()#去空白#主要人物 namelist = ['郭嘯天','楊鐵心','冷笑','武功','包惜弱','那道人','郭靖','楊康','李萍','段天德','完顏洪烈','柯鎮(zhèn)惡','朱聰','韓寶駒','韓小瑩','鐵木真','梅超風(fēng)','黃藥師','尹志平','馬鈺','沙通天','黃蓉','穆念慈','洪七公','周伯通','歐陽(yáng)鋒','裘千仞'] #人物權(quán)重 node_size=[]#no人物權(quán)重for name in namelist :node_size.append(np.array(file.loc[file['Id'] == name, 'Weight'])[0])import networkx as nx from pylab import * import matplotlib.pyplot as plt mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['axes.unicode_minus'] = Falsedef painting(): #繪制人物親密度圖G = nx.Graph() # 繪制個(gè)人物之間的親密關(guān)系for index, row in file1.iterrows():if row['Source'] in namelist:G.add_node(row['Source']) # 添加節(jié)點(diǎn)# 將當(dāng)前人物添加進(jìn)節(jié)點(diǎn)for index, row in file1.iterrows():if (row['Source'] in namelist) & (row['Target'] in namelist):#G.add_node(row['Source'], row['Target'])G.add_weighted_edges_from([(row['Source'], row['Target'], 10*np.array(row['Weight']))])#添加權(quán)重pos = nx.shell_layout(G)print('畫(huà)出網(wǎng)絡(luò)圖像:')nx.draw(G, pos, with_labels=True, node_color=range(27), edge_color='red', node_size=node_size, alpha=0.5,width=[float(d['weight']*0.01) for (u,v,d) in G.edges(data=True)])plt.show()painting()郭靖和黃蓉果然是真愛(ài)。
分析
本次 還有些缺陷。
如郭靖和黃蓉之間還有些昵稱。如靖哥哥,蓉兒,未統(tǒng)計(jì)進(jìn)來(lái)。(主要是我懶,懶得寫(xiě)多余代碼,使他們都映射到同一個(gè)名字。如把靖哥哥、郭大哥、郭靖 全部映射到郭靖。)
作者:電氣余登武
總結(jié)
以上是生活随笔為你收集整理的NLP分析小说人物关系,找找主人公的真爱。的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: opencv+yolov3实现目标检测
- 下一篇: 粒子群算法求解无约束优化问题 源码实现