Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🎬VideoIdeas.ai - Your AI YouTube Content Factory! 🚀
Are you struggling to consistently create engaging YouTube content? 😓 Say goodbye to creator's block forever!
VideoIdeas.ai is the ultimate AI assistant that generates viral-worthy scripts, fresh video ideas, and engaging content in minutes - all in YOUR unique voice and style! 🗣️
🤖 Style Cloning Technology
📝 Complete Scripts in Minutes
💡 Endless Content Ideas
🔍 YouTube SEO Optimization
⏱️Save Hours of Planning
🎯 Strategic Growth Recommendations
📚 Read related articles: VideoIdeas.ai: The Ultimate Guide to Creating Viral YouTube Videos in Your Unique Style (2025) & VideoIdeas.ai Review: The Ultimate AI Tool for YouTube Creators in 2025
▶️ Watch YouTube video: VideoIdeas.ai– How to create viral videos in your unique style
Join thousands of creators who've revolutionized their content strategy with VideoIdeas.ai - from beginners to channels with millions of subscribers!
#YouTubeGrowth#ContentCreation#AIforCreators
Business Idea: Start a YouTube Channel💵
Content:
"📹 Business Idea: YouTube Creator
Start with your smartphone to share what you love!
How to start:
1️⃣ Pick a topic: cooking, gaming, or fitness.
2️⃣ Film simple videos (don’t overthink production!).
3️⃣ Upload consistently—1 video a week to grow your audience.
💰 How to Earn: Ads, sponsorships, affiliate marketing.
📌 Tip: Beginners can use free tools like CapCut for editing."
Hashtags: #YouTubeForBeginners#ContentCreation#VideoMarketing
📸⚠️ 30 - 31 August 2025, we bringing fresh flowers again inside our gorgeous place @laurier.design ♥️
📍The Hague, Netherlands 🇳🇱
Timeslots - on request
You can enjoy location with own team or book photosession with us as model or photographer.
Leave comment for contact and more information if interested 🥰
#portfoliodag#fotografielocatie#networking#contentcreation#styledphotoshoot#styledsession
https://www.instagram.com/p/DLhgREQM51K/?igsh=ajh2MWk1Yjc0N2Y=
🚀 AI TRENDS | YouTube Introduces AI Avatar Tool for Shorts Creators
YouTube has launched a new AI avatar tool designed for Shorts creators, allowing them to generate videos of themselves using prompts. According to NS3.AI, this feature enables creators to produce clips lasting up to eight seconds. The rollout began on Wednesday and is accessible through the YouTube app and YouTube Create. Initially, the tool is available to mobile users worldwide, excluding Europe.
#AI#YouTube#AIAvatar#Shorts#ContentCreation#MobileApp#YouTubeCreate#AITrends#TechNews#CreatorTools
Меньше недели я потратил на изучение генеративных моделей, и вот что уже получается. Задумка, усидчивость и терпение, конечно, важны. Результат может быть невероятным.
#AIVideo#GenerativeAI#RunwayML#AIContent#PikaLabs#CreativeAI#ContentCreation#TechInnovation#DigitalArt#FutureOfContent
AI Video Editor Raises $500K
Diffusion Studio has secured $500K in funding as of December 4, 2024. Their AI Video Editor simplifies video editing with advanced features such as Magic Cut, Text-Based Editing, and Instant Auto-Captioning, catering to creators and businesses aiming to enhance their video production efficiency.
#AI#VideoEditing#Funding#Technology#Creators#Influencers#Business#Automation#Software#Innovation#EditingTools#VideoProduction#TextBasedEditing#AutoCaptioning#Workflow#Engagement#Professional#ContentCreation#Creativity#Efficiency
AI Startup Hits $10K Monthly Revenue
AI project ReelFarm generates viral TikTok videos using templates. Recent success: over $10k MRR within the first month. Case study: an online store achieved 100k+ views without high production costs. Industry trend: growth in accessible, low-cost video creation tools. For aspiring project creators, checklist available.
#AI#Video#Marketing#TikTok#Startup#Viral#MRR#ContentCreation#SocialMedia#Innovation#TechTrends#Entrepreneurship#ReelFarm#DigitalMarketing#BusinessGrowth#MicroSAAS#Entrepreneurs#VideoMarketing#DIY#Creators
AI Marketer Launches for $29
Introducing Nikolai's service, MarketOwl, which provides virtual marketing teams for small businesses. The AI-driven platform automates content creation and identifies potential customers. Currently, it supports around 100 users monthly, generating about $3k in revenue. The concept originated from Nikolai's observations of small companies lacking marketing resources, expertise, and time. After initial failures with a marketing strategy MVP, he pivoted to develop the AI marketer. Engagements in a dedicated subreddit led to high conversion rates for subscriptions. Successful products arise from addressing real audience problems. To effectively enter the market, consider using the Plan-Kapkan consisting of 35 steps for launching.
#MarketOwl#AI#Marketing#ContentCreation#SmallBusiness#SaaS#VirtualTeam#Startup#Entrepreneurship#MVP#ProblemSolving#Automation#CustomerAcquisition#AudienceEngagement#Subscription#Revenue#Strategy#PlanKapkan#BusinessGrowth#MarketingTools