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

Резултати

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

Пребарај: #feed

当前筛选 #feed清除筛选
News and Tips

@NEWS_AND_TIPS · Post #2361 · 26.05.2024 г., 17:07

Hashtags Telegram #feed lite 😂😂😂 Tap on any hashtags : public posts : show as chat : congratulations you unlocked Telegram Feeds

Hashtags

☀️Beck’s☀️

@beck_blog · Post #1582 · 22.03.2021 г., 21:05

· · •🌼• · GRIDS DE INSTAGRAM · •🌼• · · En el ambiente de marketing actual de Instagram, tener una hermoso grid de Instagram es vital para el éxito de cualquier persona influyente, marca creativa o publicación. Después de todo, tu grid es la cara de tu marca; es lo primero que la gente ve cuando carga tu página de Instagram en su teléfono, tableta o computadora antes de decidir seguirte. Pero ¿que hace que un grid de Instagram sea bueno? A continuación te doy algunos consejos para conseguirlo. #tips_instagram#feed · · • • • • • · · · · • • • 🍃• • • · · · · • • • • • · ·

☀️Beck’s☀️

@beck_blog · Post #1334 · 13.02.2021 г., 14:05

· • •❄️• · GRIDS DE INSTAGRAM · •❄️• • · Hoy les hablaré de la tendencia que se gestó en Instagram de personalizar el feed de marcas y usuarios al estilo collage. Al efecto grilla que se logra en el feed con esta práctica se le llama Instagram grid layouts, rompecabezas o mosaicos. #tips_instagram#feed · · • • • • • · · · · • • • ☃️• • • · · · · • • • • • · ·

BotsGram®

@botsgram_cu · Post #4878 · 23.09.2022 г., 03:53

¿Que puede hacer este bot? @feedlio_bot Bot: fuente de noticias personal gratuita: agregue enlaces a canales interesantes y obtenga todas las publicaciones en un chat. Todos los demás canales se pueden archivar descargando la lista de diálogos. Lo que este bot puede hacer: - Sigue los canales que te interesen - Enviar todas las publicaciones nuevas a este chat. - Ahorre tiempo buscando canales entre chats personales y de trabajo #feed#canales#Seguir Idioma: Ruso ( Visto en: @BotsGram_Cu )

djangoproject

@djangoproject · Post #429 · 30.08.2017 г., 18:28

https://docs.djangoproject.com/en/1.11/ref/contrib/syndication/ The syndication #feed framework #Django comes with a high-level syndication-feed-generating framework that makes creating #RSS and #Atom feeds easy. To create any syndication feed, all you have to do is write a short Python class. You can create as many feeds as you want. Django also comes with a lower-level feed-generating API. Use this if you want to generate feeds outside of a Web context, or in some other lower-level way.

News and Tips

@NewsAndTipsNT · Post #3544 · 06.08.2025 г., 11:18

🔎Telegram May Be Quietly Testing a Feed like Feature Telegram has recently introduced a new ‘Posts’ tab in Search, allowing users to easily discover content from public channels. This update comes roughly a year after the launch of #hashtagsearch, signaling Telegram’s continued focus on improving content discoverability. This appears to be a soft launch of a potential future ‘Feed’ feature — offering users a scrollable stream of relevant #posts, possibly influenced by engagement metrics such as stars. If fully implemented, this feature could significantly boost post visibility for channels, increase ad exposure for advertisers, and enhance ad revenue opportunities for creators. All indications suggest that Telegram is gearing up to roll out a #feed-based content experience, a move that could reshape how users browse and interact on the platform.

BotsGram®

@botsgram_cu · Post #3745 · 31.03.2021 г., 14:04

¿Que puede hacer este bot? @WithqutRSSBot Este bot le permite mantenerse actualizado sobre las fuentes web que ingresó (RSS o Atom) Idioma: inglés (Visto en @botsgram_cu) #rss#feed#atom

Graph Messenger

@graphmessenger · Post #446 · 22.06.2024 г., 12:58

📄Timeline, a place where you can see all the messages from all subscribed channels. ❤️Redesigned In version 11.10.0 on June 20, 2024. 🗓Was added in version 5.0 on August 19, 2016. #features#message#timeline#feed #graph_messenger#telegram @GraphMessenger @GraphMessengerTips

News and Tips

@NEWS_AND_TIPS · Post #2363 · 26.05.2024 г., 18:19

About the recent update and future of Telegram. Based on recent updates and codes, we strongly believe that Telegram is moving in a direction similar to Twitter's. They introduced hashtag-based search/feed, which we anticipate will later evolve into a full-fledged news feed. Hashtags are also highly valuable for training AI algorithms. Furthermore, based on recent code developments, Telegram is working ona fact-checking feature, which we believe is inspired by Twitter's community notes. This tool is one of the most powerful on Twitter, and I respect and find it useful. Therefore, I consider this move by Telegram to be smart and powerful. #Hashtags#Feed#Future#Thoughts

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