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
Сумматор текста создает вторую половину текста примера, а не полное текстовое резюме в 2 предложениях плюс ключевые слов ⇐ Python
Программы на Python
1764455890
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'(?
Подробнее здесь: [url]https://stackoverflow.com/questions/79833002/text-summarizer-produces-second-half-of-exampe-text-rather-than-complete-text-su[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия