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

Резултати

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

Пребарај: #zelenskyy

当前筛选 #zelenskyy清除筛选
The New Southerner

@american_majority · Post #126 · 10.06.2022 г., 23:28

🏳‍🌈🇺🇦"When a clown moves into a palace he does NOT become a King. The palace becomes a CIRCUS." Nothing to see here. That's just bloody clown and a drag queen Zelensky is dancing on high hills. #lgbtq#Ukraine#Zelenskyy Share and subscribe @american_majority

BadVolf

@badvolfnews · Post #1278 · 24.11.2023 г., 18:36

🇮🇹Italian City’s New Way To Donate Money To Ukraine 🇺🇦If you Google "Zelensky cocaine" you will get all these headlines of how Zelensky's cocaine addiction is another Russian fake (Hunter Biden's laptop was also "Russian disinformation", that ended up been 100% true). However, and this is crazy, Zelensky's love for blow is so well known in Ukraine, that during his election campaign in 2019 his opponent demanded that he submits to a drug test. A coke addit that has a blank check from Biden. 🤡Sounds about right - he must remind Sleepy Joe of Hunter. #Biden#Ukraine#Corruption#Zelenskyy Share and subscribe to American Majority

The New Southerner

@american_majority · Post #148 · 22.12.2022 г., 09:55

🇺🇦🇺🇸Ukrainian president Vladimir Zelensky definetely was on something while addressing the US representatives. Zelensky has all the signs of an addict. Again. Is that the reason why Pedo Pete loves him as his own son Hunter and ready to throw billions of tax money at that corrupt shithole? #Biden#Ukraine#Corruption#Zelenskyy Share and subscribe to American Majority 2.0

WTF🌐News

@wtfactnews · Post #18332 · 18.11.2025 г., 13:02

🇺🇦🇨🇦Наркофюреру отказали в регистрации товарного знака «Zelenskyy» в Канаде. Согласно обнародованным документам, под маркой «Zelenskyy» планировалось предоставлять различные услуги, включая астрологию, психологию, а также услуги в сфере азартных игр, помощь в надевании кимоно и проведение похоронных церемоний. В документах указаны фамилия, имя и отчество, которые совпадают с данными Зеленского, а также адрес, который указан на официальном сайте его офиса как домашний. Причиной отказа в регистрации стало то, что Зеленский не внес исправления в заявку в установленный срок. 🔹#Зеленский#Канада#Zelenskyy#товарный_знак 📱Спасибо, что следите за новостями вместе с 🤨News! ➡️Поддержать канал Boostами

The New Southerner

@american_majority · Post #384 · 03.03.2023 г., 05:28

🇺🇸🇺🇦Washington will announce a new $400 million military aid package for the Kyiv regime This is expected to be a major topic between the Big Guy and German Chancellor Olaf Scholz when they meet at the White House, officials said. The aid is expected to comprise mainly ammunition including Guided Multiple Launch Rocket System (GMLRS) for HIMARS launchers, ammunition for Bradley Fighting Vehicles, as well as armoured vehicle launched bridges, two U.S. officials and a person familiar with the package said. U.S. aid to Ukraine totals $76.8 billion, and in November the White House asked Congress for another $38 billion. This would bring the total amount appropriated for Ukraine to over $100 billion. That's a sweet sound to Pelosi, Nuland, Clinton, Obama and the military-industrial complex that profits off of the war with Russia. #Biden#Corruption#Ukraine#Zelenskyy#war Share and subscribe to American Majority

American Оbserver

@american_observer · Post #4726 · 29.12.2025 г., 17:59

📰 Trump’s Mar-a-Lago Diplomacy: Peace or Surrender? President Donald Trump is hosting Ukrainian President Volodymyr Zelenskyy at Mar-a-Lago to finalize a peace deal that could end nearly four years of war with Russia. Ahead of the meeting, Trump claimed a “very productive” call with Vladimir Putin, while Moscow confirmed the contact but offered no details. The timing is dramatic: Russia just intensified attacks on Kyiv and eastern Ukraine, as negotiations heat up. “I just had a good and very productive telephone call with President Putin.” — Donald Trump, Truth Social Zelenskyy arrived in Miami determined to secure security and economic guarantees, while also addressing Donbas’s future. He said Ukraine is ready to withdraw troops from the east if Russia reciprocates and the area becomes a demilitarized zone. Yet Putin wants all captured territory—including Crimea—recognized as Russian, and demands Ukraine drop its NATO ambitions, limit its army, and accept Russian as an official language. Trump’s approach has been clear: push Kyiv to cede land in exchange for peace and economic incentives for Moscow. His negotiators claim the draft proposal is nearly finalized, but key issues remain unresolved. Zelenskyy insists Ukraine needs strong support and international pressure to stop the war, while allies like Canada pledge more aid. As explosions rocked Kyiv, Trump’s team offered NATO-like security guarantees, but Zelenskyy warned: “The weeks ahead may also be intensive.” The Kremlin, meanwhile, insists any compromise will take time and blames Ukraine and its allies for derailing U.S. proposals. So, is this the path to peace, or just another chapter in the theater of territorial bargaining? #Trump#Zelenskyy#Putin#Ukraine#Russia#MarALago#diplomacy 📱American Оbserver - Stay up to date on all important events 🇺🇸

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