Кодировка — различия между версиями
Ӧньӧ Лав (сёрнитанін | чӧжӧс) (Новая страница: «Как собрать статистику с помощью словаря (dict), где ключом будет предложение, а значением…») |
Ӧньӧ Лав (сёрнитанін | чӧжӧс) |
||
| Строка 1: | Строка 1: | ||
| − | |||
| − | + | import os | |
| + | from collections import Counter | ||
| + | import traceback | ||
| − | == | + | # 1. Настройка путей |
| − | + | current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| + | input_path = os.path.join(current_dir, "input.txt") | ||
| + | output_path = os.path.join(current_dir, "stats.txt") | ||
| − | + | try: | |
| − | stats = | + | # 2. Проверка наличия файла |
| + | if not os.path.exists(input_path): | ||
| + | print(f"ОШИБКА: Файл 'input.txt' не найден по пути:\n{input_path}") | ||
| + | else: | ||
| + | # 3. Чтение и подсчет | ||
| + | with open(input_path, 'r', encoding='utf-8') as f: | ||
| + | sentences = [line.strip() for line in f if line.strip()] | ||
| + | |||
| + | stats = Counter(sentences) | ||
| − | for | + | # 4. Запись результата |
| − | + | with open(output_path, 'w', encoding='utf-8') as f: | |
| + | f.write("Статистика повторов предложений:\n" + "-" * 30 + "\n") | ||
| + | for sentence, count in stats.most_common(): | ||
| + | f.write(f"{sentence}: {count}\n") | ||
| − | print( | + | print(f"Успех! Статистика сохранена в: {output_path}") |
| − | |||
| − | + | except Exception: | |
| − | + | print("Произошла критическая ошибка:") | |
| + | print(traceback.format_exc()) | ||
| − | + | finally: | |
| − | + | print("\n" + "="*30) | |
| − | + | input("Нажмите Enter, чтобы закрыть это окно...") | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
Текущая версия на 16:04, 13 рака 2026
import os
from collections import Counter
import traceback
- 1. Настройка путей
current_dir = os.path.dirname(os.path.abspath(__file__)) input_path = os.path.join(current_dir, "input.txt") output_path = os.path.join(current_dir, "stats.txt")
try:
# 2. Проверка наличия файла
if not os.path.exists(input_path):
print(f"ОШИБКА: Файл 'input.txt' не найден по пути:\n{input_path}")
else:
# 3. Чтение и подсчет
with open(input_path, 'r', encoding='utf-8') as f:
sentences = [line.strip() for line in f if line.strip()]
stats = Counter(sentences)
# 4. Запись результата
with open(output_path, 'w', encoding='utf-8') as f:
f.write("Статистика повторов предложений:\n" + "-" * 30 + "\n")
for sentence, count in stats.most_common():
f.write(f"{sentence}: {count}\n")
print(f"Успех! Статистика сохранена в: {output_path}")
except Exception:
print("Произошла критическая ошибка:")
print(traceback.format_exc())
finally:
print("\n" + "="*30)
input("Нажмите Enter, чтобы закрыть это окно...")