-
Notifications
You must be signed in to change notification settings - Fork 0
/
page_rank.py
48 lines (40 loc) · 1.38 KB
/
page_rank.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# -*- coding: utf-8 -*-
from nltk.tokenize import sent_tokenize
import networkx as nx
import json
from math import log
import nltk
BLOG_DATA = 'feed.json'
def sentences(text):
return sent_tokenize(text)
def connect(nodes):
""" Return a list of edges connecting the nodes,
where the edges are given a weight based on their
similarity.
"""
return [(start, end, similarity(start, end))
for start in nodes
for end in nodes
if start is not end]
def similarity(c1, c2):
""" Return the amount of similarity between two chunks"""
return len(common_words(c1, c2)) / (log(len(words(c1))) + log(len(words(c2))))
def rank(nodes, edges):
""" Return a dictionary containing the scores for each vertex"""
graph = nx.DiGraph()
graph.add_nodes_from(nodes)
graph.add_weighted_edges_from(edges)
return nx.pagerank(graph)
def summarize(text, num_summaries=5):
""" Create a small summaries of a larger text."""
nodes = sentences(text)
edges = connect(nodes)
scores = rank(nodes, edges)
return sorted(scores)[:num_summaries]
def common_words(c1, c2):
return list(set(c1) & set(c2))
def words(c):
normalized_sentences = [s.lower() for s in c]
words = [w.lower() for sentence in normalized_sentences for w in
nltk.tokenize.word_tokenize(sentence)]
return words