Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
⚡ Jerome Powell (Chairman of the Fed):
✔ There is no recession in the USA.
❗️We may see inflation turn out to be lower than expected, in which case we would consider a Fed rate cut.
✔ A weakening labor market also suggests a faster rate cut.
✔ The Fed predicts that inflation will rise due to tariffs.
✔ Most Fed members believe it would be appropriate to cut rates later this year.
✔ So far, there are no conflicts between the Fed's dual mandates (labor market and inflation).
✔ The Fed's policy will not trigger an increase in housing supply in the long term.
❗️Banks are free to provide services to the crypto industry and conduct their activities, provided they ensure safety and reliability.
✔ I'm not worried about the latest macroeconomic data, but I am concerned about how it might change.
✔ We expect inflation to rise due to tariffs, but we do not yet know the extent of its impact on consumers. Therefore, we must wait.
✔ As long as the economy remains strong, we can afford to take a short pause.
❗️We will lower the Fed rate when the time is right.
✔ I think inflation will start to rise due to tariffs beginning in June.
✔ We will monitor the situation throughout the summer.
✔ There is no need to rush.
✔ I will not name a specific month in which we might cut the Fed rate.
✔ The Fed is simply trying to act cautiously and prudently.
✔ Economic growth will slow down this year. Immigration is one of the reasons.
✔ The dollar will remain a reserve currency for a long time.
✔ The US government bond market is functioning normally.
❗️The Fed will not tighten monetary policy or adjust the rate just because of rising oil prices. We will evaluate the entire macroeconomic picture.
✔ The dollar will remain a reserve currency for a long time.
✔ The US government bond market is functioning normally.
❗️The Fed will not tighten monetary policy or adjust the rate just because of rising oil prices. We will evaluate the entire macroeconomic picture.
✔ We are approaching price stability, but we have not quite achieved it yet.
❗️ The Fed does not have the right to buy cryptocurrency on its balance sheet and we do not seek to do so.
❗️Phs will continue to reduce balance ( #QT ).
✔ Small business lending conditions are a bit strict.
✔ We expect to see the impact of Trump's tariffs on inflation this summer.
❗️If this does not happen, we will lower the rate .
✔ We are currently in watch and wait mode.
✔ Overall, the inflation picture is quite positive.
J. Powell testifies before the House Financial Services Committee on Monetary Policy.
https://groups.google.com/forum/#!topic/pyside-dev/pqwzngAGLWE
Dear #Pyside2 contributors,
As you might know, Pyside was originally developed for Nokia while it was the owner of the #Qt technology. When Nokia sold Qt to Digia (and now The Qt Company), all the copyrights over the original Pyside code for Qt 4 got transferred to The Qt Company as well.
For different reasons, it was not possible for The Qt Company to push Pyside forward as much as we would have wished over the last few years. Fortunately this changed now, and The Qt Company is today in a position, where it can and will invest into Pyside. The goal is to ensure Pyside becomes a fully supported part of the Qt product family, with a similar development and licensing model as the rest of Qt. We want to make sure Pyside works on new Qt releases when they come out and are committed to invest long term into the technology.
A clone of Media Player Classic reimplemented in Qt for Windows desktop. It aims to reproduce most of the interface and functionality of mpc-hc while using libmpv to play video instead of DirectShow.
https://github.com/mpc-qt/mpc-qt
#windows#media#Qt
https://wiki.python.org/moin/PyQt
#PyQt is one of the two most popular Python bindings for the #Qt cross-platform #GUI/#XML/#SQL#C++ framework (another binding is #PySide).