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

Резултати

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

Пребарај: #idiot

当前筛选 #idiot清除筛选
American Оbserver

@american_observer · Post #5223 · 26.02.2026 г., 14:15

Trump Took Umbrage With De Niro’s Personal Attacks On Him 🤬🎤 Trump has responded to a recent podcast appearance by Robert De Niro, in which he called the president “an idiot.” Speaking on Monday’s episode of The Best People with Nicole Wallace, De Niro, who has long criticised the politics, morals, and competence of Trump, said: “He’s an idiot. We gotta get rid of him. He’s gonna ruin the country.” He added: “ I don’t want everybody going around with their Maga, the American flags, like they’re the only ones. We are Americans too.” The actor then took headline billing at the State of the Swamp, a Washington event intended as a riposte to Trump’s State of the Union address on Tuesday. In his emotional speech, De Niro described the president as “failing, flailing and desperate” and said he felt “betrayed by my country.” Writing at length on Truth Social on Wednesday, the president first proposed deporting representatives Ilhan Omar and Rashida Tlaib, who left the Capitol building early on Tuesday after shouting him down during his speech. Trump called them “Low IQ” and claimed they “screamed uncontrollably last night at the very elegant State of the Union, such an important and beautiful event.” “They had the bulging, bloodshot eyes of crazy people, LUNATICS, mentally deranged and sick who, frankly, look like they should be institutionalised.” He added: “They should actually get on a boat with Trump Deranged Robert De Niro, another sick and demented person with, I believe, an extremely Low IQ, who has absolutely no idea what he is doing or saying – some of which is seriously CRIMINAL!” Trump continued: “When I watched him break down in tears last night, much like a child would do, I realised that he may be even sicker than Crazy Rosie O’Donnell, who is right now in Ireland trying to figure out how to come back into our beautiful United States.” “Trump derangement syndrome” is a phrase the president has frequently used to describe his political opponents. His suggestion this was the cause of the death of the late Rob Reiner and his wife, Michele, caused considerable backlash. Shortly before Trump’s re-election in 2024, De Niro told HBO Max’s Chris Wallace that he felt Trump and his allies were “not real Republicans” and called him “a jerk, an idiot (…) and a clown.” Although not a particular fan of Kamala Harris, De Niro said that she was “at least … sensitive to the condition of the country, the people.” “She’ll make mistakes,” he continued. “Of course, everybody does, but we need somebody with the right intentions, this guy does not have the right intentions, and everybody knows that. It’s insanity. Period.” Earlier that year, the National Association of Broadcasters rescinded a leadership award it had been due to present to De Niro after the actor spoke out against Trump outside the latter’s criminal trial in New York. #trump#deNiro#idiot#maga#harris 📱American Оbserver - Stay up to date on all important events 🇺🇸

TMONK Announcements

@tmonkannouncements · Post #320 · 02.10.2025 г., 07:33

American $IDIOT × $TMONK Digital Creation Contest 🚨 Two legendary TON meme coins — $IDIOT & $TMONK — unite to launch a contest for all artists, meme-makers, designers and animators. Your task: create digital art or short videos inspired by the words of Pavel Durov. 🎭 Themes (choose one or mix them): ✨#LeadByExample → Show discipline through actions, not words. ✨#FocusOnThePositive → Spread strength & positivity, even in hard times. ✨#PrioritizeConscience → Highlight morals and conscience as timeless values. 🖌 Creative Direction: – Any medium: illustration, animation, photo art, 3D, short video. – Include $IDIOT & $TMONK in your work (graffiti, sticker, cameo, clothing, etc.). – Be creative, original, and make it memorable. 🏆 Prize for 1 Grand Winner: 🎩 TOP HAT — Uncle Sam (Telegram gift from American $IDIOT) 📖 Special e-book created by the TMONK community 📌 How to Enter: Post your creation under this official post and Tag @TmonkMonk & @AIdiot4547. Share also in: ▪️t.me/Tg_Monk ▪️t.me/AmericanIdiotBackup ⏳ Timeline: – Submission deadline: 10.10.2025 (Pavel Durov’s birthday) – Winner announced: 11.10.2025 ⚖️ Judging (100 points total): – 50 pts → Community score (likes, tags & shares on X) – 50 pts → Jury score (5 judges) on: • Creativity & originality • Connection to theme • Clever inclusion of $IDIOT & $TMONK 👉 Show your vision. Spread Monk values. Leave your mark. #LeadByExample#FocusOnThePositive#PrioritizeConscience #TON#TMONK#IDIOT