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

Резултати

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

Пребарај: #halo

当前筛选 #halo清除筛选
Mega Signals Group

@mega_pump_group · Post #1859 · 19.11.2023 г., 18:38

Pump result: Today's pump on Kucoin shocked us all with the massive volume, this was expected as we onboarded over 30,000 members in the past two weeks. However, due to unprecedented sell pressure from the #HALO team, we had expected a much larger rise in price. In fact internally we had discussed that we will be targeting around 900-1000% which we still tried to achieve with our team buying endless amounts after the first few minutes to guarantee that our members make good enough profit . Nonetheless, member's managed to profit over 150% during the signal, and with the support of our team we even managed to provide a second and third wave for extra profits which means anyone that has bought the dips during the signal had the chance to instantly make a lot of profits! We are receiving an overwhelming amount of positive messages from our community and we're happy to hear so many of you profited. From this point on, our signals will only get stronger, and you can be confident that we will use all the power we have to keep reaching higher targets. As the majority of you are aware, our greatest pump to date generated a profit for our members of around 2000%, and now our primary focus is to see if we can repeat that sort of pump. It will be quite easy to accomplish with our existing power. It can happen once again if we don't face any sell pressure coming from the coin team itself which is something that can be hard to avoid at times, hopefully we can achieve that result once again on the next one. Stay tuned for the next pump announcement.

Hashtags

Crypto Pump Club

@crypto_bitcoin_pumps_signal · Post #587 · 19.11.2023 г., 18:39

Pump result: Today's pump on Kucoin shocked us all with the massive volume, this was expected as we onboarded over 30,000 members in the past two weeks. However, due to unprecedented sell pressure from the #HALO team, we had expected a much larger rise in price. In fact internally we had discussed that we will be targeting around 900-1000% which we still tried to achieve with our team buying endless amounts after the first few minutes to guarantee that our members make good enough profit . Nonetheless, member's managed to profit over 150% during the signal, and with the support of our team we even managed to provide a second and third wave for extra profits which means anyone that has bought the dips during the signal had the chance to instantly make a lot of profits! We are receiving an overwhelming amount of positive messages from our community and we're happy to hear so many of you profited. From this point on, our signals will only get stronger, and you can be confident that we will use all the power we have to keep reaching higher targets. As the majority of you are aware, our greatest pump to date generated a profit for our members of around 2000%, and now our primary focus is to see if we can repeat that sort of pump. It will be quite easy to accomplish with our existing power. It can happen once again if we don't face any sell pressure coming from the coin team itself which is something that can be hard to avoid at times, hopefully we can achieve that result once again on the next one. Stay tuned for the next pump announcement.

Hashtags

便宜机场测速

@cheap_proxy · Post #12001 · 05.08.2025 г., 15:37

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #上海电信1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

便宜机场测速

@cheap_proxy · Post #11306 · 03.01.2025 г., 08:14

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #上海电信1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

便宜机场测速

@cheap_proxy · Post #11276 · 29.12.2024 г., 07:22

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #上海电信1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

便宜机场测速

@cheap_proxy · Post #11751 · 08.05.2025 г., 12:09

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #成都移动1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

便宜机场测速

@cheap_proxy · Post #11977 · 29.07.2025 г., 01:48

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #河北联通1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

便宜机场测速

@cheap_proxy · Post #11479 · 16.02.2025 г., 11:15

#halo#iepl#不限速#流媒体解锁#chatgpt 测速环境: #河北联通1000 新开的一家专线机场,入口很多,25r/100g,延迟属于顶级水平。因为用户量少,整体比较稳定,晚高峰速度也很快,性价比还是比较高的。 完整套餐价格图 机场地址:https://bit.ly/halo-cloud

Interesting Planet 🌍

@interesting_planet_facts · Post #415 · 25.07.2025 г., 14:22

🌎 Sun halos, circular rainbows encircling the sun, form when sunlight passes through high-altitude ice crystals. These brilliant rings are a natural spectacle, often signaling incoming weather changes. ✨ #sun⚡#halo⚡#atmosphere⚡#optics 👉subscribe Interesting Planet

ПретходнаСтраница 1 од 3Следна