🐝 PySpeller
Простая и легковесная библиотека-обёртка для API Яндекс.Спеллера. Предоставляет синхронный и асинхронный клиенты, строгую типизацию через Pydantic, и удобные функции-помощники для быстрой проверки текста.
✨ Возможности
- ✅ Проверка одного текста или списка текстов (метод
checkTexts) - ⚡ Синхронный и асинхронный режимы (на базе
httpx) - 🎛️ Поддержка всех опций Яндекс.Спеллера (игнорирование URL, цифр, повторов и т.д.)
- 🧠 Автоматическое управление HTTP-сессиями — создаются и закрываются при каждом вызове, не требуется использовать контекстный менеджер
- 📦 Типизированные модели ответов на основе Pydantic v2
- 🚨 Понятные исключения для ошибок API и сетевых проблем
- 🪶 Минимум зависимостей: только
httpxиpydantic
📦 Установка
pip install pyspeller
или с помощью uv:
uv add pyspeller
Для работы требуется Python 3.9 или новее.
🚀 Быстрый старт
Синхронная проверка
from pyspeller import check_text
result = check_text("Превед, медвед!")
if result.errors:
print(result.errors[0].suggestions) # ['Привет']
Асинхронная проверка
import asyncio
from pyspeller import async_check_text
async def main():
res = await async_check_text("синхрафазатрон")
print(res.errors[0].suggestions) # ['синхрофазотрон']
asyncio.run(main())
Проверка списка текстов
from pyspeller import check_texts
results = check_texts(["очепятка", "дубне"])
for text_result in results.results:
for error in text_result.errors:
print(f"Слово '{error.word}' → {error.suggestions}")
⚙️ Опции проверки
Все опции Яндекс.Спеллера доступны через перечисление SpellerOptions. Их можно комбинировать с помощью побитового ИЛИ (|).
from pyspeller import check_text, SpellerOptions
result = check_text(
"мой сайт http://example.com и номер R2D2",
options=SpellerOptions.IGNORE_URLS | SpellerOptions.IGNORE_DIGITS
)
# Или импортировать опции напрямую
from pyspeller import check_text, IGNORE_URLS, IGNORE_DIGITS
result = check_text(
"мой сайт http://example.com и номер R2D2",
options=IGNORE_URLS | IGNORE_DIGITS
)
Доступные опции
| Константа | Число | Описание |
|---|---|---|
IGNORE_DIGITS |
2 | Пропускать слова с цифрами |
IGNORE_URLS |
4 | Пропускать интернет-адреса и e‑mail |
FIND_REPEAT_WORDS |
8 | Находить повторяющиеся подряд слова |
IGNORE_CAPITALIZATION |
512 | Игнорировать неверное использование заглавных букв |
При необходимости можно передать произвольное целое число.
📖 API
Клиенты
YandexSpeller(lang="ru,en", options=0, format="plain")
Синхронный клиент.
Методы:
check_text(text: str) -> CheckTextResponsecheck_texts(texts: List[str]) -> CheckTextsResponse
AsyncYandexSpeller(lang="ru,en", options=0, format="plain")
Асинхронный клиент. Методы аналогичны синхронному, но возвращают корутины.
Удобные функции
# Синхронные
check_text(text, lang="ru,en", options=0, format="plain") -> CheckTextResponse
check_texts(texts, ...) -> CheckTextsResponse
# Асинхронные
async_check_text(text, ...) -> CheckTextResponse
async_check_texts(texts, ...) -> CheckTextsResponse
Все функции автоматически создают и закрывают сессию, поэтому их можно вызывать без дополнительного управления.
Модели данных
SpellResult — одна найденная ошибка
| Поле | Тип | Описание |
|---|---|---|
code |
int |
Код ошибки (1 – нет в словаре, 3 – регистр) |
pos |
int |
Позиция слова в тексте (символы) |
row |
int |
Номер строки |
col |
int |
Номер символа в строке |
length |
int |
Длина ошибочного слова |
word |
str |
Само слово |
suggestions |
List[str] |
Варианты исправления |
CheckTextResponse — результат проверки одного текста
errors: List[SpellResult]
CheckTextsResponse — результат проверки нескольких текстов
results: List[CheckTextResponse]
Исключения
Все исключения наследуются от SpellerError.
SpellerAPIError(status_code: int, message: str)– ошибка API (HTTP 4xx/5xx).SpellerNetworkError(original_exception: Exception)– сетевая ошибка (таймаут, DNS и т.п.).
🛠️ Разработка
git clone https://github.com/austnv/pyspeller.git
cd pyspeller
uv sync --group dev
uv run pytest tests/ -v
📄 Лицензия
Проект распространяется под лицензией MIT. Подробнее см. в файле LICENSE.
Сделано с ❤️ для проверки орфографии через Яндекс.Спеллер.
Metadata
Release files for pyspeller 2.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyspeller-2.0.1.tar.gz | 32.1 kB | Without provenance | Details for pyspeller-2.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyspeller-2.0.1-py3-none-any.whl | Python 3 | none | any | Details for pyspeller-2.0.1-py3-none-any.whl |
Total release size: 43.4 kB
Release files / pyspeller-2.0.1.tar.gz
| Download URL | pyspeller-2.0.1.tar.gz |
|---|---|
| Size | 32.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
46d49634e6331b3a24570f0e27284dd967261590daf27036390592e42382b978
|
|
BLAKE2b-256 checksum How to use checksums |
8b740b0901381eba5a35521e1e574815f4020358e5ba123a4db2615a8df7bcc8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / pyspeller-2.0.1-py3-none-any.whl
| Download URL | pyspeller-2.0.1-py3-none-any.whl |
|---|---|
| Size | 11.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
148664c6ceda1dd766a58ec98d1a1966d643cf1fb40dddab789e062b283cafb1
|
|
BLAKE2b-256 checksum How to use checksums |
1a8b9031c9228714c59bc0135e91beec4c35d4330618e1dec79007d053f29062
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for pyspeller 2.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.