Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
¿Quieres conocer un #datacenter por dentro?
No te pierdas este fabuloso tour virtual en 3D por uno de los centro de datos de Microsoft 👨🏽💻
https://news.microsoft.com/stories/microsoft-datacenter-tour/
Comparte 🔁este canal para que muchas personas también tengan acceso a esta información privilegida💚
La productividad esá en tiC 📲📈
📰DC1 is unstable
We aregetting reports that telegram’s datacenter in Pluto, Miami - DC1 is experiencing some issues since a few minutes ago.
The app is displaying “Updating…” at the top of the chat list, but there is no problem sending or receiving messages. This issue has only been reported for DC1.
UPDATE: Issue fixed (19:04 UTC)
#datacenter
👉The TG Times
📰Telegram is unstable
Minutes ago, the status of all Telegram datacenter has become unstable. Its exact cause is still unknown
#DataCenter
👉The TG Times
⚡️Это гигантский дата-центр Amazon за $11 млрд в Индиане.
Кампус строится под обучение и инференс ИИ и будет потреблять до 2.2 ГВт - примерно как 1 миллион домов.
В состав комплекса войдут собственные электростанции, поэтому нагрузка на местную энергосеть и тарифы для жителей должна быть минимальной.
@ai_machinelearning_big_data
#Amazon#DataCenter#AIInfrastructure#AIFactory#CloudComputing
🚀 Amazon Plans $25 Billion Data Center Investment in Mississippi
Amazon has announced plans to invest $25 billion in building a data center in Mississippi. According to Odaily, this significant investment is expected to create 2,000 jobs in the region. The initiative marks a substantial economic development for the state, promising to boost local employment and infrastructure.
#Amazon#DataCenter#Mississippi#Investment#Jobs#EconomicDevelopment#Infrastructure
OptiCore Raises $5M for AI Chips
OptiCore has secured $5M in funding to enhance its photonic chips, promising 100x energy efficiency and computing density for AI applications. This innovation aims to transform high-performance data center computing.
#OptiCore#Funding#AI#Chips#DataCenter#Efficiency#Photonics#Computing#Revolution#Performance
🚀 AI TRENDS | Anthropic Secures CoreWeave Data Center Capacity Amid Rising AI Demand
Anthropic has agreed to lease data center capacity from CoreWeave to address the growing demand for its AI services, Jin10 reports. CoreWeave announced on Friday that the multi-year agreement will assist Anthropic in building and deploying its Claude AI model. CoreWeave's CEO, Intrator, stated that the deal will involve various Nvidia chip architectures within U.S. data centers. The financial terms of the agreement were not disclosed by either company. Anthropic, similar to OpenAI, has been at the forefront of the AI service surge, sometimes struggling to maintain its products online due to what it describes as 'unprecedented demand.' Earlier this week, Anthropic revealed a collaboration with Broadcom and Google to secure 3.5 gigawatts of energy, noting that one gigawatt of power is sufficient to supply electricity to approximately 750,000 U.S. households simultaneously.
#AI#Anthropic#CoreWeave#DataCenter#ClaudeAI#Nvidia#Broadcom#Google#ArtificialIntelligence#TechTrends
🚀 AI TRENDS | CoreWeave's Junk Bonds Rise Amid Optimism from Tech Deals
CoreWeave's junk bonds experienced a rise in value due to increased market optimism following transactions with several major technology companies. According to Jin10, as of 9:05 AM New York time (21:05 UTC+8), the bonds, which have a coupon rate of 9.75% and a face value of 100 cents, increased to 101.88 cents. During the syndication process, the bond's size was expanded from the initially planned $1.25 billion. Data shows that another convertible bond issued on the same day, which was also increased to $3.5 billion, has yet to begin trading. This financing round is the latest for CoreWeave and occurred just hours after the company announced a new agreement with Meta Platforms to supply AI computing products. On Friday, Anthropic agreed to lease CoreWeave's data center capacity to meet the growing demand for its AI services. CoreWeave's stock rose more than 6% during intraday trading.
#AI#CoreWeave#JunkBonds#TechDeals#Financing#Meta#Anthropic#DataCenter#StockMarket#ConvertibleBonds