Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
📖🇪🇺 The AI Act: A Strategic Focus on SMEs
According to a summary from the Future of Life Institute the AI Act places significant emphasis on small and medium-sized enterprises (SMEs), mentioning them 38 times—far more than ‘industry’ (7) or ‘civil society’ (11). This focus translates into concrete measures: SMEs will receive priority access to regulatory sandboxes, benefit from proportional compliance costs, and have dedicated channels for guidance.
To further ease compliance, the Act introduces simplified technical documentation, SME-specific training, and tailored obligations under the Code of Practice. With these provisions, the EU aims to ensure that AI innovation remains accessible and sustainable for smaller businesses.
#AIAct#SMEs#AIRegulation#ResponsibleAI
#Opinion: Cost of Modernizing Addis: When progress pushes small businesses out
In recent years, #Ethiopia is undergoing rapid transformation, with digitalization expanding across daily life and #Addis_Abeba experiencing one of its most ambitious urban overhauls. However, Abraham Abebe Asfaw argues in this opinion piece that such ambition risks overwhelming the small and medium enterprises (#SMEs) that employ roughly 70% of the urban population.
He explains that tens of thousands of businesses are cancelling their licenses. This issue extends beyond tax compliance, as the combined pressures of taxation, informal payments, and displacement have eliminated the “margin that allowed firms to survive.”
Abraham emphasizes that “ignoring this distress is costly” and cautions that “development without guardrails risks becoming extractive rather than enabling.”
https://addisstandard.com/?p=54697
Meeting agenda: meeting Miffy? 😲
Follow along Yi Qing as she represents IRAS on the international stage in Utrecht, the Netherlands - the hometown of Miffy! 🐰
At the OECD FTA Community of Interest on Small and Medium Enterprises meeting, she connected with international peers to share experiences and perspectives. The discussions covered important ground in advancing tax administration, from strengthening digital ecosystems to e-invoicing and AI applications. These valuable insights are useful to inspire and shape IRAS' transformation journey ahead.
Explore your opportunities at IRAS today at go.gov.sg/lifeatiras
#fyp#tiktoksg#lifeatiras#SMEs#miffy
🚀 WeChat Pay Launches AI Integration Toolbox for Seamless Payment Solutions
WeChat Pay has officially introduced an AI-native integration toolbox designed to offer merchants and developers a streamlined payment integration solution. According to ChainCatcher, this toolbox facilitates the rapid generation of payment function code through natural language commands.
The toolbox comprises Skill packages, AI-friendly documentation, and APIs, enabling one-click calls in mainstream AI development environments. Its 'verbal code generation' feature significantly reduces the development process from days to minutes, allowing quick integration of over 20 functions, including mini-program payments, H5 payments, refunds, and profit-sharing.
Additionally, the toolbox includes AI diagnostic capabilities that automatically identify code logic issues and provide suggestions for fixes, minimizing financial and system risks during integration. It also supports interface troubleshooting and legacy code upgrades for existing system developers. This upgrade further advances the standardization and AI adaptation of payment capabilities, lowering the digital business barriers for small and medium-sized enterprises.
#WeChatPay#AIintegration#PaymentSolutions#Developers#Merchants#AItoolbox#CodeGeneration#DigitalBusiness#SMEs#TechInnovation#PaymentAPI#Automation#SystemUpgrade
🚀 Trident Digital Tech Holdings Partners with Ripple Strategy for African Expansion
Trident Digital Tech Holdings, a Nasdaq-listed company, has announced a strategic partnership with Ripple Strategy Holding. According to Foresight News, Ripple Strategy will provide RLUSD stablecoin technology and payment infrastructure to support Trident's business expansion in the African market.
Under the agreement, Trident plans to develop a blockchain-based tax settlement and reporting system for approximately 2.1 million small and medium-sized enterprises in Ghana. Additionally, the company aims to establish an RLUSD/GHS liquidity pool to create a low-cost, real-time foreign exchange market, facilitating 24/7 cross-border payments.
Trident has previously formed a 50/50 joint venture with local institutions in Ghana, with a stablecoin business pilot scheduled to commence by mid-2026.
#TridentDigitalTech#RippleStrategy#AfricaExpansion#Stablecoin#Blockchain#SMEs#Ghana#ForeignExchange#CrossBorderPayments#RLUSD#Nasdaq#TechPartnership#PaymentInfrastructure#BlockchainTaxSystem#LiquidityPool#XRP