TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #121 · 20 јул.

Регулярно требуется преобразовать какой-либо текст в максимально совместимый текст для 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

Резултати

Пронајдени 129 слични објави

Пребарај: #sd

当前筛选 #sd清除筛选
American Crypto©

@americancryptotrading · Post #27617 · 11.05.2026 г., 13:43

🇺🇸#SD Volumes are huge🔥 Bullish rally is coming✈️ Stader isn’t trying to be another hype project. They’re building actual staking infrastructure across multiple chains👀 $SD American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27601 · 26.04.2026 г., 14:16

🇺🇸#SD accumulating at the huge volumes🔥 Bullish🐃 People chase hype. Smart money looks at structure. Stader (SD) has: less supply + real revenue flow That matters 🚀 American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27504 · 15.01.2026 г., 13:01

🇺🇸#SD Cyclical pump is playing✈️ Do not miss $SD while it's still at the dip🔥 American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27494 · 06.01.2026 г., 13:50

🇺🇸#SD keeps to its Cycle✔️ Bear Trend is over❌Bullish Trend Started✅ MACD crosses the mid-lne as well as its signal line crossed for bullish🐃 Stader keeps staking flexible instead of locking funds. At the same time, $SD completed its buyback just yesterday🧱 https://etherscan.io/address/0xefe40ff167a89ce3babdad161d41d798ca7116b2#tokentxns American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27485 · 29.12.2025 г., 12:34

🇺🇸#SD This chart keeps repeating the same story. Sharp sell-off → momentum drains → aggressive upside leg follows. Price is now sitting right at that transition point again. 🧩 Downside move looks complete, and the curve is starting to turn — this is where new trends are born, not extended lower. 📉➡️📈 If history rhymes, the next phase is a strong expansion move. Buybacks coming soon 🔥 American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27453 · 28.11.2025 г., 13:02

🇺🇸#SD Price has completed another clean rounded bottom formation at the lower boundary of the long-term structure. The reaction from this zone is strong and mirrors previous cycle reversals. 🔥 Each prior rounded bottom led to a powerful upside expansion, and the current setup is replicating the same rhythm with high precision. The structure shows clear exhaustion of sellers and a decisive shift in momentum. ⚡️ With the pattern repeating and demand stepping in aggressively, price is now positioned for a sustained bullish continuation toward higher macro levels. The next leg up is not just likely—it’s expected. 🚀 American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27371 · 10.09.2025 г., 15:24

🇺🇸#SD/USDT Bullish Flag on weekly🐃 Looking for the retest of the MajorSupplyZone and more upside in case of a breakout🚀 Stader fundamentals keep improving — scaling TVL, expanding volumes, and consistent demand from both LST and Cabbage. This aligns with the key catalyst → buybacks roll out next week. American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27217 · 15.04.2025 г., 13:28

🇺🇸#SD/USDT Good recovery on $SD ☝️ Once we are back above the red support, send it✈️ Fundamentals: Stader released cabbage (sign for waitlist to be the first to try) + 500k coins bought from the market😎 American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27190 · 20.03.2025 г., 11:31

🇺🇸#SD/USDT Falling wedge below the resistance zone🧐 Expecting a retest of the one and breakout📈 Much Awaited Stader Quarterly Buyback happening this week - Add the fact there are no unlocks after March🔥 $SD is going full deflationary! American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27089 · 19.12.2024 г., 15:11

🇺🇸#SD/USDT Low + Higher Low We are going to break that resistance🚀 $750mln in TVL New product cabbage is coming out + Binance List added $SD American Crypto©

Hashtags

American Crypto©

@americancryptotrading · Post #27065 · 28.11.2024 г., 15:41

🇺🇸#SD/USDT We got a fakeout below the symm. triangle and now breaking out of the one📈 Whitepaper will be released at 4th December | $SD is only $50mln MC still early🔥 American Crypto©

Hashtags

Michaël Van de Poppe Official

@michaelvandepoppeanalyst · Post #4720 · 02.09.2024 г., 13:29

#SD Accumulating structure remains unchanged️ I keep accumulating! Stader buybacks 286.2k SD ($150k) off CEXs - at this rate almost 3.5% circulating supply annualised will be bought from the market BULL️

Hashtags

123•••1011
ПретходнаСтраница 1 од 11Следна