文章目錄
TextRank算法是一種文本排序算法,由谷歌的網頁重要性排序算法PageRank算法改進而來,它能夠從一個給定的文本中提取出該文本的關鍵詞、關鍵詞組,並使用抽取式的自動文摘方法提取出該文本的關鍵句。其提出論文是: Mihalcea R, Tarau P. TextRank: Bringing order into texts[C]. Association for Computational Linguistics, 2004. 論文的百度學術下載地址爲:點擊打開鏈接。
TextRank算法的基本原理:頂點擊這裏
1. textrank4zh模塊源碼解讀
textrank4zh模塊是針對中文文本的TextRank算法的python算法實現,該模塊的下載地址爲:點擊打開鏈接
對其源碼解讀如下:
util.py:textrank4zh模塊的工具包,TextRank算法的核心思想在該文件中實現。
# -*- encoding:utf-8 -*-
"""
@author: letian
@homepage: http://www.letiantian.me
@github: https://github.com/someus/
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import math
import networkx as nx
import numpy as np
import sys
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
pass
sentence_delimiters = ['?', '!', ';', '?', '!', '。', ';', '……', '…', '\n']
allow_speech_tags = ['an', 'i', 'j', 'l', 'n', 'nr', 'nrfg', 'ns', 'nt', 'nz', 't', 'v', 'vd', 'vn', 'eng']
PY2 = sys.version_info[0] == 2
if not PY2:
# Python 3.x and up
text_type = str
string_types = (str,)
xrange = range
def as_text(v): ## 生成unicode字符串
if v is None:
return None
elif isinstance(v, bytes):
return v.decode('utf-8', errors='ignore')
elif isinstance(v, str):
return v
else:
raise ValueError('Unknown type %r' % type(v))
def is_text(v):
return isinstance(v, text_type)
else:
# Python 2.x
text_type = unicode
string_types = (str, unicode)
xrange = xrange
def as_text(v):
if v is None:
return None
elif isinstance(v, unicode):
return v
elif isinstance(v, str):
return v.decode('utf-8', errors='ignore')
else:
raise ValueError('Invalid type %r' % type(v))
def is_text(v):
return isinstance(v, text_type)
__DEBUG = None
def debug(*args):
global __DEBUG
if __DEBUG is None:
try:
if os.environ['DEBUG'] == '1':
__DEBUG = True
else:
__DEBUG = False
except:
__DEBUG = False
if __DEBUG:
print(' '.join([str(arg) for arg in args]))
class AttrDict(dict):
"""Dict that can get attribute by dot"""
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def combine(word_list, window=2):
"""構造在window下的單詞組合,用來構造單詞之間的邊。
Keyword arguments:
word_list -- list of str, 由單詞組成的列表。
windows -- int, 窗口大小。
"""
if window < 2: window = 2
for x in xrange(1, window):
if x >= len(word_list):
break
word_list2 = word_list[x:]
res = zip(word_list, word_list2)
for r in res:
yield r
def get_similarity(word_list1, word_list2):
"""默認的用於計算兩個句子相似度的函數。
Keyword arguments:
word_list1, word_list2 -- 分別代表兩個句子,都是由單詞組成的列表
"""
words = list(set(word_list1 + word_list2))
vector1 = [float(word_list1.count(word)) for word in words]
vector2 = [float(word_list2.count(word)) for word in words]
vector3 = [vector1[x] * vector2[x] for x in xrange(len(vector1))]
vector4 = [1 for num in vector3 if num > 0.]
co_occur_num = sum(vector4)
if abs(co_occur_num) <= 1e-12:
return 0.
denominator = math.log(float(len(word_list1))) + math.log(float(len(word_list2))) # 分母
if abs(denominator) < 1e-12:
return 0.
return co_occur_num / denominator
def sort_words(vertex_source, edge_source, window=2, pagerank_config={'alpha': 0.85, }):
"""將單詞按關鍵程度從大到小排序
Keyword arguments:
vertex_source -- 二維列表,子列表代表句子,子列表的元素是單詞,這些單詞用來構造pagerank中的節點
edge_source -- 二維列表,子列表代表句子,子列表的元素是單詞,根據單詞位置關係構造pagerank中的邊
window -- 一個句子中相鄰的window個單詞,兩兩之間認爲有邊
pagerank_config -- pagerank的設置
"""
sorted_words = []
word_index = {}
index_word = {}
_vertex_source = vertex_source
_edge_source = edge_source
words_number = 0
for word_list in _vertex_source:
for word in word_list:
if not word in word_index:
word_index[word] = words_number
index_word[words_number] = word
words_number += 1
graph = np.zeros((words_number, words_number))
for word_list in _edge_source:
for w1, w2 in combine(word_list, window):
if w1 in word_index and w2 in word_index:
index1 = word_index[w1]
index2 = word_index[w2]
graph[index1][index2] = 1.0
graph[index2][index1] = 1.0
debug('graph:\n', graph)
nx_graph = nx.from_numpy_matrix(graph)
scores = nx.pagerank(nx_graph, **pagerank_config) # this is a dict
sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)
for index, score in sorted_scores:
item = AttrDict(word=index_word[index], weight=score)
sorted_words.append(item)
return sorted_words
def sort_sentences(sentences, words, sim_func=get_similarity, pagerank_config={'alpha': 0.85, }):
"""將句子按照關鍵程度從大到小排序
Keyword arguments:
sentences -- 列表,元素是句子
words -- 二維列表,子列表和sentences中的句子對應,子列表由單詞組成
sim_func -- 計算兩個句子的相似性,參數是兩個由單詞組成的列表
pagerank_config -- pagerank的設置
"""
sorted_sentences = []
_source = words
sentences_num = len(_source)
graph = np.zeros((sentences_num, sentences_num))
for x in xrange(sentences_num):
for y in xrange(x, sentences_num):
similarity = sim_func(_source[x], _source[y])
graph[x, y] = similarity
graph[y, x] = similarity
nx_graph = nx.from_numpy_matrix(graph)
scores = nx.pagerank(nx_graph, **pagerank_config) # this is a dict
sorted_scores = sorted(scores.items(), key=lambda item: item[1], reverse=True)
for index, score in sorted_scores:
item = AttrDict(index=index, sentence=sentences[index], weight=score)
sorted_sentences.append(item)
return sorted_sentences
if __name__ == '__main__':
pass
Segmentation.py:包含用於分詞和分句的類。
# -*-coding:utf-8-*-
# 把新版本的特性引入當前版本
from __future__ import (absolute_import, division, print_function, unicode_literals)
# 導入結巴分詞的詞性標註組件
import jieba.posseg as pseg
# 導入編碼轉換模塊
import codecs
# 導入操作系統模塊
import os
# 導入工具包組件
from textrank4zh import util
# 獲取停用詞文件的路徑
def get_default_stop_words_file():
# 獲取當前腳本所在的路徑
d = os.path.dirname(os.path.realpath(__file__))
# 返回停用詞表所在路徑,os.path.join方法用於將多個路徑組合後返回
return os.path.join(d, 'stopwords.txt')
"""分詞類"""
class WordSegmentation(object):
"""初始化函數,獲取詞性列表和停用詞表"""
def __init__(self, stop_words_file=None, allow_speech_tags=util.allow_speech_tags):
"""
:param stop_words_file:保存停用詞表的文件路徑,使用utf-8編碼方式,每行存放一個停用詞,若不是str類型,則使用默認的停用詞
:param allow_speech_tags:默認的詞性列表,用於過濾某些詞性的詞
:return:無
"""
# 詞性列表
allow_speech_tags = [util.as_text(item) for item in allow_speech_tags]
# 將詞性列表設置爲默認的詞性列表
self.default_speech_tags_filter = allow_speech_tags
# 使用set方法創建空集合
self.stop_words = set()
# 獲取停用詞文件的路徑
self.stop_words_file = get_default_stop_words_file()
# 若停用詞文件路徑不是str類型,則使用默認的停用詞
if type(stop_words_file is str):
self.stop_words_file = stop_words_file
# 打開並讀取停用詞文件,將其中的停用詞加入停用詞集合
for word in codecs.open(self.stop_words_file, 'r', 'utf-8', 'ignore'):
self.stop_words.add(word.strip())
"""對文本進行分詞,返回的分詞結果以列表方式存儲"""
def segment(self, text, lower=True, user_stop_words=True, use_speech_tags_filter=False):
"""
:param text: 要進行分詞的文本
:param lower: 是否要將單詞小寫,針對英文
:param user_stop_words: 若爲True,表示使用停用詞集合進行過濾,去掉停用詞
:param use_speech_tags_filter:是否基於詞性進行過濾,若爲True,則使用默認的詞性列表進行過濾
:return:詞性過濾後的詞列表
"""
# 待分詞的文本
text = util.as_text(text)
# 詞性標註結果列表
jieba_result = pseg.cut(text)
if use_speech_tags_filter == True:
# 進行詞性過濾後的詞性標註結果
jieba_result = [w for w in jieba_result if w.flag in self.default_speech_tags_filter]
else:
# 不進行詞性過濾的詞性標註結果
jieba_result = [w for w in jieba_result]
# 去除特殊符號
# 去除非語素字和詞兩端的空格
# 非語素字只是一個符號,字母x通常用於代表未知數、符號
word_list = [w.word.strip() for w in jieba_result if w.flag != 'x']
# 去除空字符
word_list = [word for word in word_list if len(word) > 0]
# 是否將英文單詞小寫
if lower:
word_list = [word.lower() for word in word_list]
# 是否使用停用詞集合進行過濾
if user_stop_words:
word_list = [word.strip() for word in word_list if word.strip() not in self.stop_words]
# 返回詞性過濾後的詞列表
return word_list
"""將列表sentences中的每個元素/句子轉換爲由單詞構成的列表"""
def segment_sentences(self, sentences, lower=True, user_stop_words=True, user_speech_tags_filter=False):
"""
:param sentences: 句子列表
:return: 以詞性過濾後的詞列表爲元素的列表
"""
res = []
for sentence in sentences:
# 調用segment方法,將詞性過濾後的詞列表加入到列表中
res.append(self.segment(text=sentences, lower=lower, user_stop_words=user_stop_words, use_speech_tags_filter=user_speech_tags_filter))
# 返回以詞性過濾後的詞列表爲元素的列表
return res
"""分句類"""
class SentenceSegmentation(object):
"""初始化函數,獲取用於分句的分隔符集合"""
def __init__(self, delimiters=util.sentence_delimiters):
"""
:param delimiters: 可迭代對象,用於拆分句子
"""
self.delimiters = set([util.as_text(item) for item in delimiters])
"""將文本劃分爲句子,返回句子列表"""
def segment(self, text):
# 獲取文本
res = [util.as_text(text)]
# 調試
util.debug(res)
util.debug(self.delimiters)
# 分句,使用了兩層循環
# 遍歷分隔符對象
for sep in self.delimiters:
# res表示分句結果
text, res = res, []
# 遍歷文本對象
for seq in text:
# 分句操作
res += seq.split(sep)
# 去除句子兩端空格,並濾除空句
res = [s.strip() for s in res if len(s.strip() > 0)]
# 返回句子列表
return res
"""分割類"""
class Segmentation(object):
"""初始化函數"""
def __init__(self, stop_word_file=None, allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters):
"""
:param stop_word_file: 停用詞文件
:param allow_speech_tags: 詞性列表,用於過濾某些詞性的詞
:param delimiters: 用於拆分句子的分隔符
"""
# 創建分詞類的實例
self.ws = WordSegmentation(stop_word_file=stop_word_file, allow_speech_tags=allow_speech_tags)
# 創建分句類的實例
self.ss = SentenceSegmentation(delimiters=delimiters)
def segment(self, text, lower=False):
# 獲取文本
text = util.as_text(text)
# 拆分文本,得到句子列表
sentences = self.ss.segment(text)
# 未進行詞性過濾後的詞列表
words_no_filter = self.ws.segment_sentences(sentences=sentences, lower=lower, user_stop_words=False, user_speech_tags_filter=False)
# 去掉停用詞後的詞列表
words_no_stop_words = self.ws.segment_sentences(sentences=sentences, lower=lower, user_stop_words=True, user_speech_tags_filter=False)
# 進行詞性過濾並去掉停用詞後的詞列表
words_all_filters = self.ws.segment_sentences(sentences=sentences, lower=lower, user_stop_words=True, user_speech_tags_filter=True)
# 返回以上結果
return util.AttrDict(sentences=sentences, words_no_filter=words_no_filter, words_no_stop_words=words_no_stop_words, words_all_filters=words_all_filters)
# 主模塊
if __name__ == '__main__':
# 空語句,保持程序結構的完整性
pass
TextRank4Keyword.py:包含用於提取關鍵詞和關鍵詞組的類。
#-*-coding:utf-8-*-
# 把新版本的特性引入當前版本
from __future__ import (absolute_import, division, print_function, unicode_literals)
# 導入操作複雜網絡的模塊
import networkx as nx
# 導入數值計算模塊
import numpy as np
# 導入工具包組件
from textrank4zh import util
# 導入Segmentation文件
from textrank4zh.Segmentation import Segmentation
class TextRank4Keyword(object):
"""初始化函數"""
def __init__(self, stop_words_file=None, allow_speech_tags=util.allow_speech_tags, delimiters=util.sentence_delimiters):
"""
:param stop_words_file:str類型,指定停用詞文件的路徑,若爲其他類型,則使用默認的停用詞文件
:param allow_speech_tags:詞性列表,用於過濾某些詞性的詞
:param delimiters:用於拆分句子的分隔符,默認值爲`?!;?!。;…\n`
"""
self.text = ''
self.Keywords = None
# 創建分割類的實例
self.seg = Segmentation(stop_words_file=stop_words_file, allow_speech_tags=allow_speech_tags, delimiters=delimiters)
# 句子列表
self.sentences = None
# 對sentences中每個句子分詞而得到的兩維列表
self.words_no_filter = None
# 去掉words_no_filter中的停止詞而得到的兩維列表
self.word_no_stop_words = None
# 保留words_no_stop_words中指定詞性的單詞而得到的兩維列表
self.words_all_filters = None
"""分析文本的函數,體現算法思想的部分"""
def analyze(self, text, window=2, lower=False, vertex_source='all_filters', edge_source='no_stop_words', pagerank_config={'alpha': 0.85,}):
"""
:param text: 文本內容
:param window: 窗口大小,整型,用於構造單詞之間的邊,去默認值爲2
:param lower: 是否將英文文本轉換爲小寫,默認值爲False
:param vertex_source: 選擇使用words_no_filter, words_no_stop_words, words_all_filters中的哪一個來構造pagerank對應的圖中的節點。默認值爲`'all_filters'`,可選值爲`'no_filter', 'no_stop_words', 'all_filters'`。關鍵詞也來自`vertex_source`
:param edge_source:選擇使用words_no_filter, words_no_stop_words, words_all_filters中的哪一個來構造pagerank對應的圖中的節點之間的邊。默認值爲`'no_stop_words'`,可選值爲`'no_filter', 'no_stop_words', 'all_filters'`。邊的構造要結合`window`參數。
:param pagerank_config:pagerank算法參數配置,阻尼係數爲0.85
"""
self.text = text
self.word_index = {}
self.index_word = {}
# 關鍵詞列表
self.keywords = []
self.graph = None
result = self.seg.segment(text=text, lower=lower)
self.sentences = result.sentences
self.words_no_filter = result.words_no_filter
self.word_no_stop_words = result.word_no_stop_words
self.words_all_filters = result.words_all_filters
# 調試
util.debug(20 * '*')
util.debug('self.sentences in TextRank4Keyword:\n', ' || '.join(self.sentences))
util.debug('self.words_no_filter in TextRank4Keyword:\n', self.words_no_filter)
util.debug('self.words_no_stop_words in TextRank4Keyword:\n', self.words_no_stop_words)
util.debug('self.words_all_filters in TextRank4Keyword:\n', self.words_all_filters)
# 選項,幾種模式
options = ['no_filter', 'no_stop_words', 'all_filters']
# 模式選擇
if vertex_source in options:
_vertex_source = result['words_' +vertex_source]
else:
_vertex_source = result['words_all_filters']
if edge_source in options:
_edge_source = result['words_' + edge_source]
else:
_edge_source = result['words_no_stop_words']
self.keywords = util.sort_words(_vertex_source, _edge_source, window=window, pagerank_config=pagerank_config)
"""獲取最重要的num個長度大於等於word_min_len的關鍵詞"""
def get_keywords(self, num=6, word_min_len=1):
"""
:param num: 返回的關鍵詞個數
:param word_min_len: 最小關鍵詞長度
:return: 關鍵詞列表
"""
result = []
count = 0
for item in self.keywords:
if count >= num:
break
if len(item.word) >= word_min_len:
result.append(item)
count += 1
return result
"""獲取 keywords_num 個關鍵詞構造的可能出現的短語,要求這個短語在原文本中至少出現的次數爲min_occur_num"""
def get_keyphrases(self, keywords_num=12, min_occur_num=2):
"""
:param keywords_num: 返回的關鍵詞短語個數
:param min_occur_num: 短語在文本中的最小出現次數
:return: 關鍵詞短語列表
"""
# 關鍵詞集合
keywords_set = set([item.word for item in self.get_keywords(num=keywords_num, word_min_len=1)])
# 關鍵詞短語集合
keyphrases = set()
for sentence in self.words_no_filter:
one = []
for word in sentence:
if word in keywords_set:
one.append(word)
else:
if len(one) > 1:
# 將關鍵詞組成關鍵詞短語
keyphrases.add(''.join(one))
if len(one) == 0:
continue
else:
one = []
# 兜底
if len(one) > 1:
keyphrases.add(''.join(one))
# 在原文本中至少出現min_occur_num詞
return [phrase for phrase in keyphrases if self.text.count(phrase) >= min_occur_num]
# 主模塊
if __name__ == '__main__':
# 空語句,保持程序結構的完整性
pass
TextRank4Sentence.py:包含用於提取關鍵句的類。
# -*- encoding:utf-8 -*-
"""
@author: letian
@homepage: http://www.letiantian.me
@github: https://github.com/someus/
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import networkx as nx
import numpy as np
from . import util
from .Segmentation import Segmentation
class TextRank4Sentence(object):
def __init__(self, stop_words_file=None,
allow_speech_tags=util.allow_speech_tags,
delimiters=util.sentence_delimiters):
"""
Keyword arguments:
stop_words_file -- str,停止詞文件路徑,若不是str則是使用默認停止詞文件
delimiters -- 默認值是`?!;?!。;…\n`,用來將文本拆分爲句子。
Object Var:
self.sentences -- 由句子組成的列表。
self.words_no_filter -- 對sentences中每個句子分詞而得到的兩級列表。
self.words_no_stop_words -- 去掉words_no_filter中的停止詞而得到的兩級列表。
self.words_all_filters -- 保留words_no_stop_words中指定詞性的單詞而得到的兩級列表。
"""
self.seg = Segmentation(stop_words_file=stop_words_file,
allow_speech_tags=allow_speech_tags,
delimiters=delimiters)
self.sentences = None
self.words_no_filter = None # 2維列表
self.words_no_stop_words = None
self.words_all_filters = None
self.key_sentences = None
def analyze(self, text, lower=False,
source='no_stop_words',
sim_func=util.get_similarity,
pagerank_config={'alpha': 0.85, }):
"""
Keyword arguments:
text -- 文本內容,字符串。
lower -- 是否將文本轉換爲小寫。默認爲False。
source -- 選擇使用words_no_filter, words_no_stop_words, words_all_filters中的哪一個來生成句子之間的相似度。
默認值爲`'all_filters'`,可選值爲`'no_filter', 'no_stop_words', 'all_filters'`。
sim_func -- 指定計算句子相似度的函數。
"""
self.key_sentences = []
result = self.seg.segment(text=text, lower=lower)
self.sentences = result.sentences
self.words_no_filter = result.words_no_filter
self.words_no_stop_words = result.words_no_stop_words
self.words_all_filters = result.words_all_filters
options = ['no_filter', 'no_stop_words', 'all_filters']
if source in options:
_source = result['words_' + source]
else:
_source = result['words_no_stop_words']
self.key_sentences = util.sort_sentences(sentences=self.sentences,
words=_source,
sim_func=sim_func,
pagerank_config=pagerank_config)
def get_key_sentences(self, num=6, sentence_min_len=6):
"""獲取最重要的num個長度大於等於sentence_min_len的句子用來生成摘要。
Return:
多個句子組成的列表。
"""
result = []
count = 0
for item in self.key_sentences:
if count >= num:
break
if len(item['sentence']) >= sentence_min_len:
result.append(item)
count += 1
return result
if __name__ == '__main__':
pass
2 textrank4zh模塊的使用
2.1 textrank4zh模塊的安裝
這裏介紹幾種安裝Python模塊的方法,僅供參考。
1)python setup.py install --user
2)sudo python setup.py install
3)pip install textrank4zh --user
4)sudo pip install textrank4zh
textrank4zh模塊在python2或python3中均可使用,它所依賴的其他模塊要求滿足:
jieba >= 0.35; numpy >= 1.7.1;networkx >= 1.9.1
2.2 textrank4zh的使用實例
因爲操作比較簡單,所有直接以代碼的形式展示例子,代碼在python3環境下親測可用。
1)提取關鍵詞、關鍵短語和關鍵句
#-*-coding:utf-8-*-
"""
@author:taoshouzheng
@time:2018/5/18 8:20
@email:[email protected]
"""
# 導入系統模塊
import sys
# imp模塊提供了一個可以實現import語句的接口
from imp import reload
# 異常處理
try:
# reload方法用於對已經加載的模塊進行重新加載,一般用於原模塊有變化的情況
reload(sys)
# 設置系統的默認編碼方式,僅本次有效,因爲setdefaultencoding函數在被系統調用後即被刪除
sys.setdefaultencoding('utf-8')
except:
pass
"""
展示textrank4zh模塊的主要功能:
提取關鍵詞
提取關鍵短語(關鍵詞組)
提取摘要(關鍵句)
"""
# 導入編碼轉換模塊
import codecs
# 從textrank4zh模塊中導入提取關鍵詞和生成摘要的類
from textrank4zh import TextRank4Keyword, TextRank4Sentence
# 待讀取的文本文件,一則新聞
file = r'C:\Users\Tao Shouzheng\Desktop\01.txt'
# 打開並讀取文本文件
text = codecs.open(file, 'r', 'utf-8').read()
# 創建分詞類的實例
tr4w = TextRank4Keyword()
# 對文本進行分析,設定窗口大小爲2,並將英文單詞小寫
tr4w.analyze(text=text, lower=True, window=2)
"""輸出"""
print('關鍵詞爲:')
# 從關鍵詞列表中獲取前20個關鍵詞
for item in tr4w.get_keywords(num=20, word_min_len=1):
# 打印每個關鍵詞的內容及關鍵詞的權重
print(item.word, item.weight)
print('\n')
print('關鍵短語爲:')
# 從關鍵短語列表中獲取關鍵短語
for phrase in tr4w.get_keyphrases(keywords_num=20, min_occur_num=2):
print(phrase)
print('\n')
# 創建分句類的實例
tr4s = TextRank4Sentence()
# 英文單詞小寫,進行詞性過濾並剔除停用詞
tr4s.analyze(text=text, lower=True, source='all_filters')
print('摘要爲:')
# 抽取3條句子作爲摘要
for item in tr4s.get_key_sentences(num=3):
# 打印句子的索引、權重和內容
print(item.index, item.weight, item.sentence)
結果如下:
關鍵詞爲:
媒體 0.02155864734852778
高圓圓 0.020220281898126486
微 0.01671909730824073
賓客 0.014328439104001788
趙又廷 0.014035488254875914
答謝 0.013759845912857732
謝娜 0.013361244496632448
現身 0.012724133346018603
記者 0.01227742092899235
新人 0.01183128428494362
北京 0.011686712993089671
博 0.011447168887452668
展示 0.010889176260920504
捧場 0.010507502237123278
禮物 0.010447275379792245
張傑 0.009558332870902892
當晚 0.009137982757893915
戴 0.008915271161035208
酒店 0.00883521621207796
外套 0.008822082954131174
關鍵短語爲:
微博
>摘要爲:
0 0.07097195571711616 中新網北京12月1日電(記者 張曦) 30日晚,高圓圓和趙又廷在京舉行答謝宴,諸多明星現身捧場,其中包括張傑(微博)、謝娜(微博)夫婦、何炅(微博)、蔡康永(微博)、徐克、張凱麗、黃軒(微博)等
6 0.05410372364148859 高圓圓身穿粉色外套,看到大批記者在場露出嬌羞神色,趙又廷則戴着鴨舌帽,十分淡定,兩人快步走進電梯,未接受媒體採訪
27 0.04904283129838876 記者瞭解到,出席高圓圓、趙又廷答謝宴的賓客近百人,其中不少都是女方的高中同學
2)展示textrank4zh模塊的三種分詞模式的效果
三種分詞模式分別爲:
words_no_filter模式:簡單分詞,不剔除停用詞,不進行詞性過濾
words_no_stop_words模式:剔除停用詞
words_all_filters模式(默認):即剔除停用詞,又進行詞性過濾
#-*-coding:utf-8-*-
"""
@author:taoshouzheng
@time:2018/5/18 14:52
@email:[email protected]
"""
import codecs
from imp import reload
from textrank4zh import TextRank4Keyword, TextRank4Sentence
import sys
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except:
pass
"""測試3類分詞的效果"""
text = '這間酒店位於北京東三環,裏面擺放很多雕塑,文藝氣息十足。答謝宴於晚上8點開始。'
tr4w = TextRank4Keyword()
tr4w.analyze(text=text, lower=True, window=2)
# 將文本劃分爲句子列表
print('sentences:')
for s in tr4w.sentences:
print(s)
print('\n')
# 對句子列表中的句子進行分詞,不進行詞性過濾
print('words_no_filter:')
# words爲詞列表,tr4w.words_no_filter爲由詞列表組成的列表
for words in tr4w.words_no_filter:
print('/'.join(words))
print('\n')
# 打印去掉停用詞的詞列表
print('words_no_stop_words:')
for words in tr4w.words_no_stop_words:
print('/'.join(words))
print('\n')
# 打印去掉停用詞並進行詞性過濾之後的詞列表
print('words_all_filters:')
for words in tr4w.words_all_filters:
print('/'.join(words))
結果如下:
<span style="font-family:SimSun;">sentences:
這間酒店位於北京東三環,裏面擺放很多雕塑,文藝氣息十足
答謝宴於晚上8點開始
words_no_filter:
這/間/酒店/位於/北京/東三環/裏面/擺放/很多/雕塑/文藝/氣息/十足
答謝/宴於/晚上/8/點/開始
words_no_stop_words:
間/酒店/位於/北京/東三環/裏面/擺放/很多/雕塑/文藝/氣息/十足
答謝/宴於/晚上/8/點
words_all_filters:
酒店/位於/北京/東三環/擺放/雕塑/文藝/氣息
答謝/宴於/晚上</span>
值得參考的文章,附上鍊接如下: