import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from heapq import nlargest
def summarize_text(text, num_sentences):
"""
Summarizes a text by extracting the most important sentences.
Args:
text: The text to be summarized.
num_sentences: The number of sentences to include in the summary.
Returns:
A list of the most important sentences in the text.
"""
# Tokenize the text into sentences
sentences = nltk.sent_tokenize(text)
# Remove stop words and punctuation from each sentence
stop_words = set(stopwords.words('english'))
filtered_sentences = []
for sentence in sentences:
words = word_tokenize(sentence)
filtered_words = [word for word in words if word.lower() not in stop_words and word.isalnum()]
filtered_sentences.append(' '.join(filtered_words))
# Calculate word frequencies in each sentence
word_frequencies = {}
for sentence in filtered_sentences:
for word in word_tokenize(sentence):
if word not in word_frequencies:
word_frequencies[word] = 0
word_frequencies[word] += 1
# Calculate sentence scores based on word frequencies
sentence_scores = {}
for i, sentence in enumerate(filtered_sentences):
for word in word_tokenize(sentence):
if word in word_frequencies:
if i not in sentence_scores:
sentence_scores[i] = 0
sentence_scores[i] += word_frequencies[word]
# Select the top 'num_sentences' sentences with the highest scores
top_sentences = nlargest(num_sentences, sentence_scores, key=sentence_scores.get)
# Return the summary sentences
return [sentences[i] for i in top_sentences]
# Example usage
text = """
This is a sample text to be summarized. It contains multiple sentences about different topics.
The main idea is to extract the most important sentences and create a concise summary.
This is another sentence that is less important than the previous ones.
However, it still contributes to the overall meaning of the text.
Finally, this is the last sentence of the text.
"""
summary = summarize_text(text, 2)
# Print the summary
print("Summary:")
for sentence in summary:
print(sentence)
Explanation:
Import necessary libraries:
nltk: For sentence tokenization, stop word removal, and word tokenization.
heapq: For selecting the top sentences based on their scores.
summarize_text function:
Takes the text to summarize and the desired number of sentences as input.
Sentence Tokenization: Splits the text into individual sentences.
Stop Word Removal: Removes common, less meaningful words (like "a", "the", "is") to focus on key words.
Word Frequency Calculation: Counts the frequency of each word in the text.
Sentence Scoring: Assigns a score to each sentence based on the frequency of its words. Sentences with more frequent words are considered more important.
Top Sentence Selection: Uses nlargest to select the num_sentences sentences with the highest scores.
Summary Construction: Returns the selected sentences as the summary.
Example Usage:
Defines a sample text.
Calls the summarize_text function to generate a summary with 2 sentences.
Prints the summary.
Key Points:
This implementation uses a simple word frequency-based approach, which may not be the most sophisticated summarization technique.
You can experiment with different sentence scoring methods (e.g., TF-IDF) for improved results.
The number of sentences in the summary is a parameter that you can adjust based on your needs.
To Use the Code:
Install NLTK:pip install nltk
Download NLTK Data: Run nltk.download('punkt') and nltk.download('stopwords') in your Python environment to download necessary resources.
Paste the code into a Python file and run it.
This code provides a basic foundation for sentence summarization. You can further customize and improve it by exploring more advanced techniques and libraries.
“write a code for the summarizer of sentences using Python. make it perfect and it should….” Conversation with gemini-1.5-flash-api-0514, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m8506a737vph5sa74vjbqhav