Сумматор текста создает вторую половину текста примера, а не полное текстовое резюме в 2 предложениях плюс ключевые словPython

Программы на Python
Ответить
Anonymous
 Сумматор текста создает вторую половину текста примера, а не полное текстовое резюме в 2 предложениях плюс ключевые слов

Сообщение Anonymous »

App.py запускается и создает функцию счетчика. Однако он выводит вторую половину примера текстового файла вики вместо сводки, созданной сценарием model.py. App.py и model.py — это два отдельных файла. Намерение состояло в том, чтобы создать языковую модель, которая использует статистику для получения сводных результатов. Где ошибка?
App.py:
import argparse # Input analysis (parsing) processed with grammar.
import sys # System exit.
import os # File path.
import time # Timestamping.

# Import (AI text summarization and load text file) functions from called upon modules.
from .model import summarize_text
from .utils import load_text

# Spinner animation for longer operations. Heighten user experience, (UX).
def spinner():
# Function to cycle through characters.
while True:
for frame in "|/-\\":
yield frame

# Define main CLI function as script runs.
def main():
# Initialize parser (analysis) with description.
parser = argparse.ArgumentParser(
description="AI-powered text summarizer CLI tool"
)
# Input the text file we want to consolidate.
parser.add_argument(
"input_file",
type=str,
help="Path to the text file you want to summarize"
)
# Output text file naming.
parser.add_argument(
"-o", "--output",
type=str,
help="Optional output file to save the summary"
)
# Allow for plenty of, (verbose), documentation of each step of process (ideal for teaching and auditing).
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="Enable verbose mode for detailed logs"
)

# Analyse the user argument.
args = parser.parse_args()

# Qualify input file.
if not os.path.exists(args.input_file):
print(f"Error: File not found: {args.input_file}")
sys.exit(1)

# Load and read text file.
if args.verbose:
print(f"[INFO] Loading file: {args.input_file}")
text = load_text(args.input_file)

# Prevent empty file summarization.
if not text.strip():
print("Error: File is empty. Cannot summarize an empty text file.")
sys.exit(1)

# Show summarization is rendering
if args.verbose:
print("Generating summary...")

# Display spinner.
spin = spinner()
for _ in range(10):
sys.stdout.write(next(spin))
sys.stdout.flush()
time.sleep(0.05)
sys.stdout.write("\b")

# Executive AI summarization.
summary = summarize_text(text)

# Print summary to console.
print("\n=== SUMMARY RESULT ===\n")
print(summary)

# Save output to file if requested.
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(summary)

print(f"\n Summary saved to: {args.output}")

# Direct execution only.
if __name__ == "__main__":
main()

model.py:
import re
from collections import Counter

def summarize_text(text):
"""
Lightweight extractive summarizer:
- Extracts sentences
- Computes keyword frequency
- Selects best 1–2 sentences
- Produces a clean, grammatical summary
"""

# --- 1. Split text into sentences ---
sentences = [s.strip() for s in re.split(r'(?

Подробнее здесь: https://stackoverflow.com/questions/798 ... te-text-su
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»