Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
🚀 Jamie Dimon Warns of Rising U.S. Debt Risks and Global Deficits
Jamie Dimon has expressed concerns over the increasing risks associated with U.S. debt. According to NS3.AI, Dimon referenced a Congressional Budget Office forecast predicting that the debt-to-GDP ratio will escalate from the current 100% to 120% by 2036. He highlighted that global deficits are currently at 5%, despite the relatively healthy state of the global economy. Dimon also cautioned that a future downturn in the credit cycle could lead to higher-than-anticipated losses in leveraged lending.
#USDebt#GlobalDeficits#DebtToGDP#CreditRisk#LeveragedLending#EconomicForecast
🚀 Global Currency Order Restructuring May Lead to Long-Term Dollar Depreciation
According to Jin10, a report by China International Capital Corporation (CICC) suggests that after the short-term factors boosting the dollar fade, the narrative of global currency order restructuring and the weakening of dollar hegemony may once again dominate market direction. The United States' continuous accumulation of net external debt increases its need for dollar depreciation. The uncertainty surrounding U.S. President Donald Trump's policies and the unresolved risks of dollar 'weaponization' also dampen market demand for U.S. assets. The new Federal Reserve Chair, Walsh, advocates for a 'balance sheet reduction' policy, which could objectively help restore the dollar's credibility if implemented. However, Walsh's policy is constrained by the resilience of the real economy and financial markets, as well as political limitations. Additionally, Trump's foreign, trade, and economic policies continue to negatively impact the dollar's credibility. Considering the overall impact of Walsh and Trump's policies, it is difficult to conclude that the dollar's credibility will improve in the future. We anticipate that the global currency order may continue to restructure, driving the dollar to maintain a long-term depreciation trend.
#GlobalCurrencyOrder#DollarDepreciation#USDebt#DollarHegemony#FederalReserve#MonetaryPolicy#TrumpPolicies#CICCReport#FinancialMarkets#CurrencyRestructuring
🚀 U.S. Public Debt Increases by $571.28 Billion, Reaching $38.969 Trillion
The United States public debt has increased by approximately $571.28 billion this year, reaching a total of $38.969 trillion as of April 7, 2026. According to NS3.AI, this figure encompasses both debt held by the public and intragovernmental holdings. In an interview with NPR, JPMorgan Chase CEO Jamie Dimon expressed concerns that the growing debt burden could pose challenges, potentially leading to higher market rates and reduced demand for U.S. Treasurys.
#USDebt#PublicDebt#USFinance#GovernmentDebt#EconomicNews#USMarkets#Treasury#DebtCrisis#JPMorgan#Macroeconomics
#The_Barron's 🇺🇸📕[PDF]⬇️
13 #October2025
#Weekly_Magazines
For learning, for free(dom).
@backupofmagazines
In this issue, Oracle founder #LarryEllison takes center stage, betting big on #AIInvestment in what may be his boldest move yet. The issue unpacks market jitters over a tech-driven bull run, rising #Gold and #USDebt, and the resilience of #ESG investing. Insights span #Ferrari’s EV gamble, #ImmigrationEconomics, and potential Fed leadership shifts. For savvy investors, Barron’s explores where the smart money is heading—plus, a special “Guide to Wealth” offers survival strategies for volatility. #Oracle#StockMarket#EllisonUnbound#TechBubble#Barrons#RetirementPlanning