Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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
Binance, the world's largest cryptocurrency exchange, has achieved a major milestone in Indonesia. The company's subsidiary has successfully obtained a regulatory license from the Indonesian authorities, paving the way for expanded operations and increased legitimacy in the country.
#Bullish🔥
#BTC, did multiple retest back to the zone and kinda have it break and retest. Price already rejecting the zone multiple times, which is sort of #bullish as of now. #ETFs also get approvals, good to see price sustaining over the zone. Well, if #Bitcoin remains silent over this, then we can see a good rally in alts soon.
By Crypto Australia
⚡️ Sentiment notes a decrease in the number of wallets with a non-zero balance 🪙#BTC, which may mean that some participants will enter the cache before the US elections. The experts of #Sentiment consider this development of the situation to be #bullish for #BTC after the elections are held...
📈Bullish Pattern - Three White Soldiers.
A. How to recognise it?
• There must be a preceding downtrend.
• Three consecutive long green candles observed.
• The second and third candle opens within the body of the preceding one but closes higher than the preceding one.
B. What is the psychology behind?
•The first long green candle signals that the bears are exhausted after the prolonged downtrend and the bulls start to take over. The bulls continue the rally with the subsequent two candles closing higher.
C. How do we trade it?
• Look for the Three White Soldiers at the bottom of a downtrend.
•Wait for the fourth candle to close above the high of the third candle to confirm the reversal.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the first green candle.
#patterns
#fibonacciacademy
#bullish
@fibonaccisyndicate.
Channel: BULLISH CRYPTO ( VIP OFFICIAL )
Members: ~2.69K
💢 Username: @officialbullishcrypto
Description:
At Bullish Crypto Comumnity! You can find tested strategies, powerful tools, and experienced traders to arm you with knowledge.
🏷 Tags: #crypto_fx_trading
#crypto#bullish#signals#investment#money
https://telegramchannels.me/channels/officialbullishcrypto
Despite the bear market, DWF Labs is choosing to double down on crypto innovations.
"I think the key to #innovation in #Web3 is decentralization. Many projects that we are seeing and decided to invest into, are bringing to the table real decentralization value.
We have experienced massive #tech acceleration especially during crypto winter or previous bear cycles.
That is why we are so #bullish about funding the next wave of #crypto innovation. This year alone, we funded more than 50 projects."
- Andrei Grachev (Managing Partner, DWF Labs)
Read full interview here.
📈Bullish Pattern - PIERCING
A. How to recognise it?
• There must be a preceding downtrend.
• A red candle followed by a green candle.
• The green candle opens with a gap-down and closes at 50% or above of the real body of red candle.
B. What is the psychology behind?
• The red candle implies the control of the bears following a prolonged downtrend.
• In next session, the market opens below the low of the red candle, suggesting continuation of the bearish forces.
• The bears then lose momentum, the bulls conquer and lead the price up during the session, and eventually manage to cover 50% losses or more from the previous session.
C. How do we trade it?
• Look for the Piercing at the bottom of a downtrend.
• Wait for the next candle to close above the high of the green candle to confirm the existence of bullish force.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the green candle.
#patterns#bullish#trading#fibonacciacademy
@fibonaccisyndicate
📈Bullish Pattern - HAMMER🔨
A. How to recognise it?
• There must be a preceding downtrend
• It looks like a square lollipop with a long stick.
• The closing price is above or near the opening price, forming a tiny body.
• The real body could be green or red. It has no or little upper shadow.
• The lower shadow is at least twice of the length of the real body.
B. What is the psychology behind?
• Similarly to Dragonfly Doji, when the market opens, the bears continuously drag the price down during the session, resulting in a long lower shadow.
• The bulls fight strongly and conquer the bears by pushing the price above or near the opening level, forming a little square body.
• The longer the lower shadow, the more effective the bullish signal. It tells us that the bulls are strong enough to conquer the bears who once dragged the price so low.
C. How do we trade it?
• Look for the Hammer at the bottom of a downtrend.
• Wait for the next candle to close above the high of the Hammer to confirm the existence of bullish force.
• Open a long position upon confirmation.
• Place a stop-loss below the low of the Hammer.
#patterns#bullish#trading#fibonacciacademy
@fibonaccisyndicate
📈Bullish Pattern - Dragonfly Doji
A. How to recognise it?
•There must be a preceding downtrend.
• It looks like a T letter.
• The opening, highest and closing price are same.
• It has no real body but a long lower shadow.
B. What is the psychology behind?
• When the market opens, the bears drag the price all the way down, resulting in a long lower shadow. • The bulls fight strongly and eventually manage to push the price back up to the opening level. • The longer the lower shadow, the more effective the bullish signal. It tells us that the bulls are strong enough to conquer the bears who once dragged the price so low.
C. How do we trade it?
• Look for the Dragonfly Doji at the bottom of a downtrend. • Wait for the next candle to close above the high of the Dragonfly Doji to confirm the existence of bullish force. • Open a long position upon confirmation. • Place a stop-loss below the low of the Dragonfly Doji.
#patterns
#fibonacciacademy
#bullish
#trading
@fibonaccisyndicate