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

Резултати

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

Пребарај: #dating

当前筛选 #dating清除筛选
PUBITY

@Pubity · Post #13 · 09.09.2024 г., 18:24

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

UNCLE

@Uncle · Post #13 · 29.07.2024 г., 09:33

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

MAMA

@mama · Post #12 · 29.07.2024 г., 09:28

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

Trump's Ear

@trumpsear_tg · Post #1586 · 01.10.2025 г., 16:00

“Charmer” Barron Trump reserves an entire floor of Trump Tower for a date Speculation is brewing around young Barron Trump’s personal life as the young bachelor begins his sophomore year in college. Just last month insiders claimed young Trump was focusing on business endeavours, and turned his back on dating. But it seems someone has caught his eye, although the identity of the mysterious lady remains undisclosed. Barron’s classmates say he had no trouble attracting young women since arriving at university. “He’s tall and awkward, but he was the thing, the guy. He had a lot of girls running after him,” one insider said. Another classmate mentioned, “He’s definitely a charmer. He’s very popular among the ladies. He’s tall and good-looking, and many people find him quite attractive.” Of course, dates with the president’s son would be anything but ordinary. Reportedly, the young bachelor shut down an entire floor of his father’s tower for a romantic date. But reportedly it was more than a grand gesture. According to sources, young Trump had no choice but to have his date at home, given the tight security measures to ensure his safety. The decision to shut down the entire floor of the building was made with Barron and his date’s safety in mind. #BarronTrump#dating 👂More on Trump's Ear ⚠️

CADILLAC

@cadillac · Post #113 · 28.07.2024 г., 11:13

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

China

@China · Post #18 · 29.07.2024 г., 08:14

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

Chevron

@chevron · Post #12 · 29.07.2024 г., 09:25

Dating App – the first dating app in Telegram to find your Crush in the places you love ❤️ @datingapp #dating#love

Hashtags

TON Crypto News

@toncoin_rap · Post #92 · 31.08.2024 г., 07:46

🎧⤴ TON Dating Unleashes New Filters—Are They Revolutionizing Online Matchmaking? - New Filters:TON Dating introduces advanced filters including industry, height, eye color, and zodiac sign. Age and location filters now have an automatic expansion option. - Enhanced Matching: Improved visibility for interest matches and likes, making it easier to find mutual connections. Men can also filter to see only those who liked them. - User Experience: A new profile preview feature lets users see how their profiles appear to others. Registration for men no longer requires an Instagram account, simplifying the process. Verse 1: Filters on deck, yeah, I'm swiping with finesse, Height, zodiac, eyes—got my standards, nothing less. Profiles poppin', see who likes you in a sec, Match, earn that Toncoin, yeah, we chasing that check. Chorus: Swipe right, match tight, filters in the night, Crypto in my wallet, future looking bright. TON's the app, making moves, keeping it tight, Find your match, make it last, everything's in sight. Verse 2: No 'gram needed, just a smile and a vibe, Men, you know who likes you, keep that energy high. Interest matches lit, common ground we can't deny, On this blockchain journey, love and money coincide. Chorus: Swipe right, match tight, filters in the night, Crypto in my wallet, future looking bright. TON's the app, making moves, keeping it tight, Find your match, make it last, everything's in sight. Bridge: From the chat to the heart, blockchain sets us apart, Earnin' while you lovin', that's the realest art. Step up your game, don't let this chance slip away, TON Dating's the wave, it's a brand-new day. #TONDating #Dating #Ton 🎧@toncoin_rap

Libreware

@libreware · Post #1049 · 26.02.2022 г., 15:52

Alovoa open source online dating Application Meet new, exciting people! alovoa is a free and open source dating application that respects your privacy.A TWP compatible browser is needed for the best Experience Compatible :- fennec,Firefox,iceraven,chrome. Incompatible :- Bromite Download - https://www.f-droid.org/packages/com.alovoa.alovoa/ https://github.com/Alovoa/alovoa-android #New#internet#dating @foss_Android

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