1. 程式人生 > >Python:帶你走進哈利波特的魔法世界

Python:帶你走進哈利波特的魔法世界

最近有將近一個月的時間沒更新了,並不是小文有心地偷懶,而是實在是有太多的磚要搬了(不多說了,等會還要繼續搬-_-!!)......因為最近的專案涉及到文字分析(jieba包)以及人物關係分析(gephi),因此今天就整理總結一下,以哈利波特七部曲(國慶假期看的)為例,分享一下個人的使用心得。

先簡單介紹一下jieba中文分詞包,jieba包主要有三種分詞模式:

  • 精確模式:預設情況下是精確模式,精確地分詞,適合文字分析;
  • 全模式:把所有能成詞的詞語都分出來, 但是詞語會存有歧義;
  • 搜尋引擎模式:在精確模式的基礎上,對長詞再次切分,適合用於搜尋引擎分詞。

jieba包常用的語句:

  • 精確模式分詞:
    jieba.cut(text,cut_all = False),當cut_all = True時為全模式
  • 自定義詞典:jieba.load_userdict(file_name)
  • 增加詞語:jieba.add_word(seg,freq,flag)
  • 刪除詞語:jieba.del_word(seg)

《哈利·波特》是英國作家J·K·羅琳的奇幻文學系列小說,描寫主角哈利·波特在霍格沃茨魔法學校7年學習生活中的冒險故事。下面將以《哈利波特》錯綜複雜的人物關係為例,實踐一下jieba包。

#載入所需包
import numpy as np
import pandas as pd
import jieba,codecs
import jieba.posseg as pseg  #標註詞性模組
from pyecharts import Bar,WordCloud

#匯入人名、停用詞、特定詞庫
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')

#定義一個分詞函式
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)]  #篩選出人物名字

#統計詞頻
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

經過初次分詞之後,我們發現大部分的詞語已經ok了,但是還是有小部分名字類的詞語分得不精確,比如說'布利'、'羅恩說'、'伏地'、'斯內'、'地說'等等,還有像'烏姆裡奇'、'霍格沃茲'等分成兩個詞語的。

#自定義部分詞語
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('斯內')

#再次分詞
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

再次分詞之後,我們可以看到在初次分詞出現的錯誤已經得到修正了,接下來我們統計分析。

#統計詞頻TOP15的詞語
bar = Bar('出現最多的詞語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

整部小說出現最多的詞語TOP15中出現了哈利、赫敏、羅恩、鄧布利多、魔杖、魔法、馬爾福、斯內普和小天狼星等字眼,我們自己串一下,大概可以知道《哈利波特》的主要內容了,就是哈利在小夥伴赫敏、羅恩的陪伴下,經過大法師鄧布利多的幫助與培養,利用魔杖使用魔法把大boss伏地魔k.o的故事。當然啦,《哈利波特》還是非常精彩的,請原諒小文拙劣的概括。

#統計人物名字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

整部小說按照出場次數,我們發現哈利作為主角的地位無可撼動,比排名第二的赫敏遠超13000多次,當然這也是非常正常的,畢竟這本書是《哈利波特》,而不是《赫敏格蘭傑》。

#整本小說的詞語詞雲分析
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

#人物關係分析
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]

處理之後,我們發現同一個人物出現了不同的稱呼,因此合併並統計,得出88個節點。

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)

有了節點node以及邊edge後,通過gephi對《哈利波特》的人物關係進行分析:

(節點的大小表示人物的出場次數,線的粗細表示人物之間的交往關係)

ok,今天就介紹到這裡,有什麼意見或者建議請第一時間告訴小文哦,繼續搬磚去了。。