Заменить кавычки на типографские
Расставляет парные кавычки в русском или английском стиле, не трогая код и HTML-теги.
Что делает скрипт
Скрипт определяет язык по кириллице и выбирает русские или английские кавычки. Блоки кода, инлайн-код и HTML-теги пропускаются, апострофы внутри слов остаются на месте. Результат можно вывести на экран, сохранить в новый файл или применить с копией .bak.
- С --in-place исходный файл заменяется, рядом остаётся копия .bak.
Быстрый старт
python smart_quotes.py article.md --output styled.md
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python smart_quotes.py article.mdpython smart_quotes.py article.md --style en --output styled.mdpython smart_quotes.py article.md --in-place
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
smart_quotes.py
#!/usr/bin/env python3
"""Типографские кавычки для русского и английского текста."""
from __future__ import annotations
import argparse
import re
import shutil
from pathlib import Path
FENCE = re.compile(r"^\s*(```|~~~)")
PROTECTED = re.compile(r"(`[^`\n]+`|<[^>\n]+>)")
def convert_segment(text: str, style: str) -> str:
if style == "ru":
double_open, double_close = "\u00ab", "\u00bb"
else:
double_open, double_close = "\u201c", "\u201d"
single_open, single_close, apostrophe = "\u2018", "\u2019", "\u2019"
result = []
for index, char in enumerate(text):
previous = text[index - 1] if index > 0 else " "
following = text[index + 1] if index + 1 < len(text) else " "
if char == '"':
opening = previous.isspace() or previous in "([{<"
result.append(double_open if opening else double_close)
elif char == "'":
if previous.isalnum() and following.isalnum():
result.append(apostrophe)
elif previous.isspace() or previous in "([{<":
result.append(single_open)
else:
result.append(single_close)
else:
result.append(char)
return "".join(result)
def process(text: str, style: str) -> str:
output = []
in_fence = False
for line in text.splitlines():
if FENCE.match(line):
in_fence = not in_fence
output.append(line)
continue
if in_fence:
output.append(line)
continue
parts = PROTECTED.split(line)
converted = []
for part in parts:
if part.startswith(("`", "<")):
converted.append(part)
else:
converted.append(convert_segment(part, style))
output.append("".join(converted))
return "\n".join(output) + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description="Заменить кавычки на типографские")
parser.add_argument("input", type=Path, help="Входной файл")
parser.add_argument("--output", type=Path, help="Выходной файл")
parser.add_argument("--style", choices=["auto", "ru", "en"], default="auto", help="Стиль кавычек")
parser.add_argument("--in-place", 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")
style = args.style
if style == "auto":
style = "ru" if re.search(r"[А-Яа-яЁё]", text) else "en"
result = process(text, style)
if args.in_place:
backup = source.with_name(source.name + ".bak")
shutil.copy2(source, backup)
source.write_text(result, encoding="utf-8")
print(f"Стиль: {style}, копия: {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"Стиль: {style}, результат: {target}")
else:
print(result, end="")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.