Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для URL, имени файла, имени объекта в каком-то софте и тд. Требования совместимости простые: в тексте должны быть только допустимые символы. Обычно это a-z, 0-9 и "_" или "-". То есть, только прописные буквы латинского алфавита и цифры (как пример).
Допустим, нам нужно название статьи в блоге преобразовать в slug для добавления его в URL этой статьи. Как это лучше всего сделать?
В Django по умолчанию есть готовая функция slugify для таких случаев.
Но я её никогда не использую. Почему? Потому что её недостаточно!
Приведём пример
>>> from django.utils.text import slugify
>>> slugify('This is a Title')
'this-is-a-title'
Пока всё отлично
>>> slugify('This is a "Title!"')
'this-is-a-title'
Спец символы удалились, всё хорошо.
>>> slugify('Это заголовок статьи')
''
Вот и приехали 😢. Если текст не английский то буквы просто игнорируются. Можно это поправить
>>> slugify('Это заголовок статьи', allow_unicode=True)
'это-заголовок-статьи'
Но тогда мы не вписываемся в условие. У нас появилась кириллица в тексте.
Так как я часто пишу сайты для русскоязычных пользователей эта проблема весьма актуальна. Я не использую стандартную функцию и всегда пишу свою.
Оригинал я не беру в расчёт и пишу полностью свою функцию. И так, по порядку:
🔸1. Исходный текст:
>>> text = 'Мой заголовок №10 😁!'
Взял специально посложней со специальными символами.
🔸2. Транслит
Необходимо сделать транслит всех символов в латиницу. Здесь очень выручает библиотека unidecode. Помимо простого транслита кириллицы в латиницу она умеет преобразовывать спец символы и иероглифы в текстовые аналоги.
from unidecode import unidecode
>>> unidecode("Ñ Σ ® µ ¶ ¼ 月 山")
'N S (r) u P 1/4 Yue Shan'
Очень крутая библиотека, советую👍
В нашем случае получаем такое преобразование:
>>> text = unidecode(text)
>>> print(text)
'Moi zagolovok No. 10 !'
Отличный транслит. Смайл просто удалился, хотя я ждал что-то вроде :). Ну и ладно, всë равно невалидные символы.
А еще наш код уже поддерживает любой язык, будь то хинди или корейский.
🔸4. Фильтр символов
Unidecode не занимается фильтрацией по недопустимым символам. Это мы делаем в следующем шаге через regex. Просто заменим все символы на "_" если они вне указанного диапазона.
>>> text = re.sub(r'[^a-zA-Z0-9]+', '_', text)
>>> print(text)
'Moi_zagolovok_No_10_'
Символ "+" в паттерне выручает когда несколько недопустимых символов идут рядом. Все они заменяются на один символ "_".
🔸5. Slugify
Осталось удалить лишние символы по краям и сделать нижний регистр
>>> text = text.strip('_').lower()
>>> print(text)
'moi_zagolovok_no_10'
Получаем отличный slug! 😎
🌎 Полный код в виде функции.
______________
PS. Проверку что в строке остался хоть один допустимый символ я бы вынес в отдельную функцию.
#libs#tricks#django
#VITE/USDT analysis :
#VITE is currently in an uptrend, consistently making higher lows. The price is bouncing back from the 200-period exponential moving average (EMA) following a retracement to this level. This behavior indicates that the price is expected to maintain its bullish momentum and potentially test higher levels. For a long position, it is advisable to wait for a break above the $0.01365 level before entering the trade.
TF : 4H
Entry : $0.01365
Target : $0.01600
SL : $0.01213
#vue#admin_tempalte#art_design_pro#vite#vue_element_admin#vue3#vue3_admin
Art Design Pro is a free, open-source tool for building admin systems. It uses the latest technology and offers a beautiful interface, making it easy to create high-quality admin systems. You can customize themes and use many features like global search, multi-language support, and rich text editing. This helps developers build systems that are both visually appealing and user-friendly, saving time and effort in development.
https://github.com/Daymychen/art-design-pro
#typescript#cloudflare_kv#cloudflare_pages#cloudflare_workers#drizzle_orm#postgres#remix#tailwindcss#typescript#vite
Supermemory lets you easily save and organize information from websites, PDFs, text, and apps like Google Drive or Notion. You can then chat with your saved memories in natural language to quickly find what you need. It connects with popular AI tools, automatically updates your data, and creates smart knowledge graphs to help you remember and use your information better. This saves you time and effort by keeping all your important content in one place and making it easy to access and search whenever you want. It’s like having a personal assistant for your digital memory.
https://github.com/supermemoryai/supermemory
#typescript#agent#browser_use#computer_use#electron#gui_agents#mcp#mcp_server#vision#vite#vlm
Agent TARS is a powerful tool that helps automate tasks using AI. It integrates with many tools and can handle complex tasks like web scraping and data analysis. This makes it easier to manage workflows and reduces errors. Users can automate tasks in just a few steps, making it very efficient. Agent TARS also supports advanced browser operations and has a user-friendly desktop app, which makes it easy to use for anyone. Overall, it helps users save time and work more efficiently.
https://github.com/bytedance/UI-TARS-desktop
#vue#javascript#music#music_library#music_player#musicplayer#pinia#splayer#vite#vue#vue3
SPlayer is a simple, open-source music player designed mainly for Windows, built with modern web technologies like Vue 3 and Electron. It supports features like login via QR code or phone, daily check-ins, desktop lyrics, local music management, playlist creation, cloud music upload and playback, and even plays some songs without copyright restrictions. It offers light/dark themes, music spectrum visualization, and supports high-quality downloads if you have the right membership. You can deploy it locally or on servers using Docker or Vercel. This player is free for personal use and encourages community contributions, helping you enjoy and organize music easily with a customizable, modern interface.
https://github.com/imsyy/SPlayer
#python#ai#bug_detection#code_audit#code_quality#code_review#developer_tools#devsecops#google_gemini#llm#react#sast#security_scanner#supabase#typescript#vite#vulnerability_scanner#xai
**DeepAudit** is an AI-powered code audit tool using multi-agent collaboration to deeply scan projects for vulnerabilities like SQL injection, XSS, and path traversal. Import code from GitHub/GitLab or paste snippets; agents plan, analyze with RAG knowledge, and verify issues via secure Docker sandbox PoCs, generating PDF reports with fix suggestions. Deploy easily with one Docker command, supports local Ollama models for privacy, and cuts traditional tools' high false positives. **You benefit** by automating secure audits like a pro hacker—saving time, reducing errors, ensuring real exploits are caught, and speeding safe releases without manual hassle.
https://github.com/lintsinghua/DeepAudit
#typescript#app#cap#coss#loom#mac#nextjs#nextjs14#open_source#oss#react#record#screen_capture#screen_recorder#screenshot#solidjs#tauri#tauri_app#typescript#vite
Cap is a free, open-source tool that helps you record and share videos quickly. It's similar to Loom but gives you more control over your recordings. You can use it on both macOS and Windows, making it easy to work with different devices. Cap allows you to store your videos locally or in the cloud, which means you can access them from anywhere. This tool is great for sharing information with teams or clients securely and efficiently.
https://github.com/CapSoftware/Cap