先簡單介紹一下jieba中文分詞包师崎,jieba包主要有三種分詞模式:
- 精確模式:默認(rèn)情況下是精確模式咐柜,精確地分詞师骗,適合文本分析;
- 全模式:把所有能成詞的詞語都分出來, 但是詞語會存有歧義妇智;
- 搜索引擎模式:在精確模式的基礎(chǔ)上滥玷,對長詞再次切分,適合用于搜索引擎分詞巍棱。
jieba 包常用的語句:
- 精確模式分詞:jieba.cut(text,cut_all = False)惑畴,當(dāng)cut_all = True時為全模式
- 自定義詞典:jieba.load_userdict(file_name)
- 增加詞語:jieba.add_word(seg,freq,flag)
- 刪除詞語:jieba.del_word(seg)
《哈利·波特》是英國作家J·K·羅琳的奇幻文學(xué)系列小說,描寫主角哈利·波特在霍格沃茨魔法學(xué)校7年學(xué)習(xí)生活中的冒險故事航徙。下面將以《哈利波特》錯綜復(fù)雜的人物關(guān)系為例如贷,實踐一下jieba包。
#加載所需包
import numpy as np
import pandas as pd
import jieba,codecs
import jieba.posseg as pseg #標(biāo)注詞性模塊
from pyecharts import Bar,WordCloud
#導(dǎo)入人名到踏、停用詞杠袱、特定詞庫
renmings = pd.read_csv('人名.txt',engine='python',encoding='utf-8',names=['renming'])['renming']
stopwords = pd.read_csv('mystopwords.txt',engine='python',encoding='utf-8',names=['stopwords'])['stopwords'].tolist()
book = open('哈利波特.txt',encoding='utf-8').read()
jieba.load_userdict('哈利波特詞庫.txt')
#定義一個分詞函數(shù)
def words_cut(book):
words = list(jieba.cut(book))
stopwords1 = [w for w in words if len(w)==1] #添加停用詞
seg = set(words) - set(stopwords) - set(stopwords1) #過濾停用詞,得到更為精確的分詞
result = [i for i in words if i in seg]
return result
#初次分詞
bookwords = words_cut(book)
renming = [i.split(' ')[0] for i in set(renmings)] #只要人物名字窝稿,出掉詞頻以及詞性
nameswords = [i for i in bookwords if i in set(renming)] #篩選出人物名字
#統(tǒng)計詞頻
bookwords_count = pd.Series(bookwords).value_counts().sort_values(ascending=False)
nameswords_count = pd.Series(nameswords).value_counts().sort_values(ascending=False)
bookwords_count[:100].index
經(jīng)過初次分詞之后霞掺,我們發(fā)現(xiàn)大部分的詞語已經(jīng)ok了,但是還是有小部分名字類的詞語分得不精確讹躯,比如說'布利'、'羅恩說'缠劝、'伏地'潮梯、'斯內(nèi)'、'地說'等等惨恭,還有像'烏姆里奇'秉馏、'霍格沃茲'等分成兩個詞語的。
#自定義部分詞語
jieba.add_word('鄧布利多',100,'nr')
jieba.add_word('霍格沃茨',100,'n')
jieba.add_word('烏姆里奇',100,'nr')
jieba.add_word('拉唐克斯',100,'nr')
jieba.add_word('伏地魔',100,'nr')
jieba.del_word('羅恩說')
jieba.del_word('地說')
jieba.del_word('斯內(nèi)')
#再次分詞
bookwords = words_cut(book)
nameswords = [i for i in bookwords if i in set(renming)]
bookwords_count = pd.Series(bookwords).value_counts().sort_values(ascending=False)
nameswords_count = pd.Series(nameswords).value_counts().sort_values(ascending=False)
bookwords_count[:100].index
再次分詞之后脱羡,我們可以看到在初次分詞出現(xiàn)的錯誤已經(jīng)得到修正了萝究,接下來我們統(tǒng)計分析免都。
#統(tǒng)計詞頻TOP15的詞語
bar = Bar('出現(xiàn)最多的詞語TOP15',background_color = 'white',title_pos = 'center',title_text_size = 20)
x = bookwords_count[:15].index.tolist()
y = bookwords_count[:15].values.tolist()
bar.add('',x, y,xaxis_interval = 0,xaxis_rotate = 30,is_label_show = True)
bar
整部小說出現(xiàn)最多的詞語TOP15中出現(xiàn)了哈利、赫敏帆竹、羅恩绕娘、鄧布利多、魔杖栽连、魔法险领、馬爾福、斯內(nèi)普和小天狼星等字眼秒紧。
我們自己串一下绢陌,大概可以知道《哈利波特》的主要內(nèi)容了,就是哈利在小伙伴赫敏熔恢、羅恩的陪伴下脐湾,經(jīng)過大法師鄧布利多的幫助與培養(yǎng),利用魔杖使用魔法把大boss伏地魔k.o的故事叙淌。當(dāng)然啦秤掌,《哈利波特》還是非常精彩的。
#統(tǒng)計人物名字TOP20的詞語
bar = Bar('主要人物Top20',background_color = 'white',title_pos = 'center',title_text_size = 20)
x = nameswords_count[:20].index.tolist()
y =nameswords_count[:20].values.tolist()
bar.add('',x, y,xaxis_interval = 0,xaxis_rotate = 30,is_label_show = True)
bar
整部小說按照出場次數(shù)凿菩,我們發(fā)現(xiàn)哈利作為主角的地位無可撼動机杜,比排名第二的赫敏遠(yuǎn)超13000多次,當(dāng)然這也是非常正常的衅谷,畢竟這本書是《哈利波特》椒拗,而不是《赫敏格蘭杰》。
#整本小說的詞語詞云分析
name = bookwords_count.index.tolist()
value = bookwords_count.values.tolist()
wc = WordCloud(background_color = 'white')
wc.add("", name, value, word_size_range=[10, 200],shape = 'diamond')
wc
#人物關(guān)系分析
names = {}
relationships = {}
lineNames = []
with codecs.open('哈利波特.txt','r','utf8') as f:
n = 0
for line in f.readlines():
n+=1
print('正在處理第{}行'.format(n))
poss = pseg.cut(line)
lineNames.append([])
for w in poss:
if w.word in set(nameswords):
lineNames[-1].append(w.word)
if names.get(w.word) is None:
names[w.word] = 0
relationships[w.word] = {}
names[w.word] += 1
for line in lineNames:
for name1 in line:
for name2 in line:
if name1 == name2:
continue
if relationships[name1].get(name2) is None:
relationships[name1][name2]= 1
else:
relationships[name1][name2] = relationships[name1][name2]+ 1
node = pd.DataFrame(columns=['Id','Label','Weight'])
edge = pd.DataFrame(columns=['Source','Target','Weight'])
for name,times in names.items():
node.loc[len(node)] = [name,name,times]
for name,edges in relationships.items():
for v, w in edges.items():
if w > 3:
edge.loc[len(edge)] = [name,v,w]
處理之后获黔,我們發(fā)現(xiàn)同一個人物出現(xiàn)了不同的稱呼蚀苛,因此合并并統(tǒng)計,得出88個節(jié)點玷氏。
node.loc[node['Id']=='哈利','Id'] = '哈利波特'
node.loc[node['Id']=='波特','Id'] = '哈利波特'
node.loc[node['Id']=='阿不思','Id'] = '鄧布利多'
node.loc[node['Label']=='哈利','Label'] = '哈利波特'
node.loc[node['Label']=='波特','Label'] = '哈利波特'
node.loc[node['Label']=='阿不思','Label'] = '鄧布利多'
edge.loc[edge['Source']=='哈利','Source'] = '哈利波特'
edge.loc[edge['Source']=='波特','Source'] = '哈利波特'
edge.loc[edge['Source']=='阿不思','Source'] = '鄧布利多'
edge.loc[edge['Target']=='哈利','Target'] = '哈利波特'
edge.loc[edge['Target']=='波特','Target'] = '哈利波特'
edge.loc[edge['Target']=='阿不思','Target'] = '鄧布利多'
nresult = node['Weight'].groupby([node['Id'],node['Label']]).agg({'Weight':np.sum}).sort_values('Weight',ascending = False)
eresult = edge.sort_values('Weight',ascending = False)
nresult.to_csv('node.csv',index = False)
eresult.to_csv('edge.csv',index = False)
有了節(jié)點node以及邊edge后堵未,通過gephi對《哈利波特》的人物關(guān)系進行分析:
節(jié)點的大小表示人物的出場次數(shù),線的粗細(xì)表示人物之間的交往關(guān)系
歡迎大家加入小編創(chuàng)建的Python行業(yè)交流群盏触,有大牛答疑渗蟹,有資源共享,有企業(yè)招人赞辩!是一個非常不錯的交流基地雌芽!群號:556370268