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

Резултати

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

Пребарај: #nuland

当前筛选 #nuland清除筛选
BadVolf

@BadvolfNews · Post #546 · 28.02.2023 г., 09:50

🇫🇷Victoria Nuland knew about the far right militias in Ukraine, but concealed the fact - French report. A bloodthirsty regime change initiator, the deaths of many hundreds of thousands started with her 'cookies in Kiev' moment. #Nuland#Ukraine Share and subscribe to American Majority

BadVolf

@BadvolfNews · Post #83 · 19.05.2022 г., 15:11

🇺🇸Actually, that is a really interesting video. Remember how during Senate testimony, Biden and Obama official Victoria Nuland admitted there were biological research labs in Ukraine? Victoria Nuland told Senator Marco Rubio: “Ukraine has biological research facilities which we are now quite concerned Russian troops, Russian forces may be seeking to gain control of.” Nuland said so under oath. Why didn’t Victoria "cookies of freedom" Nuland just say there aren’t any bioweapons? Hint: there are bioweapons. If she would have lied, she would go to jail. So just look, what we have. Here's another document we got from our whistleblower. Read it carefully. So there's a reason why Blinken literally stops her from visiting Russia and answering their questions. Ms. Nuland needs to be questioned again, but this time by a Special Counsel and under the penalty of perjury. Russia and China want their questions to be answered too! #Ukraine#bioweapon#biolab#Nuland Share and subsribe @american_majority

BadVolf

@BadvolfNews · Post #97 · 25.05.2022 г., 20:00

⚡BREAKING⚡ 🇺🇸🇺🇦Nuland-Pyatt Tape Removed From YouTube After 8 Years The smoking gun proving U.S. involvement in the 2014 coup in Kiev has been removed from YouTube after eight years, Consortium news reported. The removal of a video happend just a few days later after the American majority channel published another leaked letter from Nuland's office and this proves its authenticity. It was the most complete version of the leaked conversation between then Assistant Secretary of State Victoria Nuland and Geoffrey Pyatt, the then U.S. ambassador to Ukraine, in which the two discuss who will make up the new government weeks before democratically-elected Ukrainian President Viktor Yanukovych was overthrown in a violent coup on Feb. 21, 2014. The U.S. State Department never denied the authenticity of the video, and even issued an apology to the European Union after Nuland is heard on the tape saying, “Fuck the E.U.” SMELL THE PANIC #Ukraine#bioweapon#biolab#Nuland#leak Share and subsribe @american_majority

The New Southerner

@american_majority · Post #121 · 25.05.2022 г., 20:17

⚡BREAKING⚡ 🇺🇸🇺🇦Nuland-Pyatt Tape Removed From YouTube After 8 Years The smoking gun proving U.S. involvement in the 2014 coup in Kiev has been removed from YouTube after eight years, Consortium news reported. The removal of a video happend just a few days later after the American majority channel published another leaked letter from Nuland's office and this proves its authenticity. It was the most complete version of the leaked conversation between then Assistant Secretary of State Victoria Nuland and Geoffrey Pyatt, the then U.S. ambassador to Ukraine, in which the two discuss who will make up the new government weeks before democratically-elected Ukrainian President Viktor Yanukovych was overthrown in a violent coup on Feb. 21, 2014. The U.S. State Department never denied the authenticity of the video, and even issued an apology to the European Union after Nuland is heard on the tape saying, “Fuck the E.U.” SMELL THE PANIC #Ukraine#bioweapon#biolab#Nuland#leak Share and subsribe @american_majority