Нормализовать пробелы в тексте
Схлопывает повторяющиеся пробелы и табы, убирает хвосты строк и бережёт блоки кода.
Что делает скрипт
Скрипт проходит по тексту, заменяет серии пробелов и табов одним пробелом и очищает концы строк. Блоки кода в Markdown по умолчанию остаются нетронутыми, а отступы можно сохранить отдельным флагом. Запись идёт в новый файл или через --in-place с копией .bak.
- С --in-place исходный файл заменяется, рядом остаётся копия .bak.
Быстрый старт
python normalize_spaces.py article.md --output clean.md
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python normalize_spaces.py article.md --output clean.mdpython normalize_spaces.py notes.txt --keep-indent --tab-width 4python normalize_spaces.py article.md --in-place
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
normalize_spaces.py
#!/usr/bin/env python3
"""Нормализация пробелов и табуляции в тексте."""
from __future__ import annotations
import argparse
import re
import shutil
from pathlib import Path
FENCE = re.compile(r"^\s*(```|~~~)")
def normalize_line(line: str, keep_indent: bool, tab_width: int) -> str:
if not line.strip():
return ""
indent = re.match(r"[ \t]*", line).group(0)
body = line[len(indent):]
body = re.sub(r"[ \t]+", " ", body).strip()
if keep_indent and body:
return indent.expandtabs(tab_width) + body
return body
def process(text: str, keep_indent: bool, tab_width: int, protect_code: bool) -> str:
output = []
in_fence = False
for line in text.splitlines():
if protect_code and FENCE.match(line):
in_fence = not in_fence
output.append(line)
continue
if in_fence:
output.append(line)
continue
output.append(normalize_line(line, keep_indent, tab_width))
return "\n".join(output).rstrip("\n") + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description="Нормализовать пробелы в тексте")
parser.add_argument("input", type=Path, help="Входной файл")
parser.add_argument("--output", type=Path, help="Выходной файл, по умолчанию stdout")
parser.add_argument("--in-place", action="store_true", help="Заменить исходный файл")
parser.add_argument("--keep-indent", action="store_true", help="Сохранить отступы слева")
parser.add_argument("--tab-width", type=int, default=4, help="Ширина табуляции")
parser.add_argument("--no-protect-code", action="store_true", help="Обрабатывать и блоки кода")
args = parser.parse_args()
source = args.input.expanduser()
if not source.is_file():
parser.error(f"Файл не найден: {source}")
if args.in_place and args.output:
parser.error("С --in-place не указывайте --output")
if args.output and args.output.expanduser().resolve() == source.resolve():
parser.error("Выходной файл совпадает с входным, используйте --in-place")
text = source.read_text(encoding="utf-8")
result = process(text, args.keep_indent, args.tab_width, not args.no_protect_code)
if args.in_place:
backup = source.with_name(source.name + ".bak")
shutil.copy2(source, backup)
source.write_text(result, encoding="utf-8")
print(f"Файл обновлён, копия: {backup.name}")
elif args.output:
target = args.output.expanduser()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(result, encoding="utf-8")
print(f"Результат: {target}")
else:
print(result, end="")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.