Preparing TextRank implementation plan
The plan is to implement TextRank fully in Python using only standard libraries, including sentence splitting via regex, a minimal stopword list, sentence similarity based on shared words, building a weighted graph as a similarity matrix, running an iterative PageRank, and selecting top-ranked sentences for the summary. Next, I'll produce the complete, self-contained code accordingly.
Below is a self‑contained Python implementation of the TextRank algorithm for extractive summarization. It:
- Splits text into sentences with a simple regex.
- Computes pairwise sentence similarity based on shared non‑stopword tokens.
- Builds a weighted graph where nodes are sentences and edge weights are similarities.
- Runs a PageRank‑style power iteration to score sentences.
- Returns the top‑ranked sentences as the summary.
import re
import math
from collections import defaultdict
# A very basic English stopword list to down‑weight uninformative words
STOPWORDS = {
"a", "an", "the", "and", "or", "but", "if", "while", "is", "are", "was",
"were", "in", "on", "at", "to", "of", "for", "with", "as", "by", "it",
"this", "that", "these", "those", "from", "be", "been", "has", "have",
"had", "he", "she", "they", "we", "you", "i", "not", "no", "so", "too",
"can", "could", "will", "would", "should"
}
def split_sentences(text):
"""Split text into sentences using punctuation as delimiters."""
# This is a simple splitter; for production use a proper sentence tokenizer.
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
# Remove any empty strings
return [s.strip() for s in sentences if s.strip()]
def sentence_similarity(s1, s2, stopwords=None):
"""
Compute similarity between two sentences based on shared words.
Returns 0 if there are no shared words.
"""
if stopwords is None:
stopwords = set()
# Tokenize on words and lowercase
words1 = [w for w in re.findall(r'\w+', s1.lower()) if w not in stopwords]
words2 = [w for w in re.findall(r'\w+', s2.lower()) if w not in stopwords]
if not words1 or not words2:
return 0.0
set1, set2 = set(words1), set(words2)
intersection = set1 & set2
if not intersection:
return 0.0
# Normalize by log lengths to dampen effect of long sentences
return len(intersection) / (math.log(len(set1) + 1e-10) + math.log(len(set2) + 1e-10))
def build_similarity_matrix(sentences, stopwords=None):
"""Build a matrix of sentence similarities."""
n = len(sentences)
sim_matrix = [[0.0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
if i != j:
sim_matrix[i][j] = sentence_similarity(sentences[i], sentences[j], stopwords)
return sim_matrix
def pagerank(sim_matrix, damping=0.85, max_iter=100, tol=1e-4):
"""
Run a simple PageRank power iteration on the similarity graph.
sim_matrix should be an NxN matrix of non‑negative weights.
"""
n = len(sim_matrix)
scores = [1.0 / n] * n # initial scores
for _ in range(max_iter):
new_scores = [(1.0 - damping) / n] * n
for i in range(n):
# Sum incoming scores weighted by edge weight / outdegree
for j in range(n):
weight_ji = sim_matrix[j][i]
if weight_ji == 0:
continue
out_weight_sum = sum(sim_matrix[j])
if out_weight_sum == 0:
continue
new_scores[i] += damping * (weight_ji / out_weight_sum) * scores[j]
# Check convergence
delta = sum(abs(new_scores[i] - scores[i]) for i in range(n))
scores = new_scores
if delta < tol:
break
return scores
def textrank_summarize(text, top_n=3, stopwords=None):
"""
Summarize the input text by returning the top_n ranked sentences.
"""
if stopwords is None:
stopwords = STOPWORDS
sentences = split_sentences(text)
if len(sentences) <= top_n:
return " ".join(sentences)
sim_matrix = build_similarity_matrix(sentences, stopwords)
scores = pagerank(sim_matrix)
# Rank sentences by score
ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
# Select the top_n sentence indices and sort them to preserve original order
top_indices = sorted(idx for idx, _ in ranked[:top_n])
summary_sentences = [sentences[idx] for idx in top_indices]
return " ".join(summary_sentences)
# Example usage
if __name__ == "__main__":
text = (
"TextRank is an algorithm based on PageRank, used for keyword extraction and text summarization. "
"It builds a graph of words or sentences and uses graph‑based ranking to find important elements. "
"In summarization, sentences are nodes, and edges reflect similarity. "
"The most central sentences according to PageRank are selected as the summary."
)
print(textrank_summarize(text, top_n=2))
This implementation is intentionally simple: it uses a basic tokenizer and a small stopword list. For better results on real‑world data, you may want to use a more robust sentence tokenizer and a larger stopword list (e.g. from NLTK), and experiment with different similarity functions.