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

Резултати

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

Пребарај: #araghchi

当前筛选 #araghchi清除筛选
Turchia e dintorni

@notizieturchia · Post #3790 · 28.02.2026 г., 15:19

Ministro degli Esteri iraniano #Araghchi: "Siamo pronti per una de-escalation, ma prima bisogna fermare l'aggressione, prima bisogna fermare gli attacchi. E poi c'è la possibilità di colloqui, e possiamo prenderla in considerazione".

Hashtags

RT en français

@RTenfrancais · Post #80196 · 27.04.2026 г., 13:45

▶️Rencontre entre Vladimir #Poutine et Abbas #Araghchi, représentant spécial du président de la République islamique d'Iran et ministre iranien des Affaires étrangères 📱Regarder sur VKontakte RT en français • Osez questionner !

RT en français

@RTenfrancais · Post #80190 · 27.04.2026 г., 13:14

🇷🇺🇮🇷Rencontre entre Vladimir #Poutine et le ministre iranien des Affaires étrangères, Abbas #Araghchi. Aux côtés du président russe se trouvent également le ministre russe des Affaires étrangères Sergueï Lavrov, le chef de la Direction principale du renseignement de l’état-major des forces armées russes Igor Kostioukov et le conseiller présidentiel Iouri Ouchakov. Poutine a indiqué avoir reçu la semaine dernière un message du guide suprême iranien Mojtaba Khamenei. RT en français • Osez questionner !

RT en français

@RTenfrancais · Post #80188 · 27.04.2026 г., 12:39

⏺Préparatifs de la rencontre entre Vladimir #Poutine et Abbas #Araghchi à la Bibliothèque présidentielle de Saint-Pétersbourg RT en français • Osez questionner !

RT France actualités

@rt_fra · Post #40890 · 08.05.2026 г., 13:21

💬#Téhéran défend la voie diplomatique Le chef de la diplomatie iranienne Abbas #Araghchi estime que les États-Unis choisissent l’escalade militaire au moment même où une issue diplomatique devient possible. Selon lui, la pression exercée contre l’Iran ne fera pas céder Téhéran et risque au contraire d’éloigner davantage toute perspective de règlement politique. RT en français • Osez questionner !

RT France actualités

@rt_fra · Post #40681 · 06.05.2026 г., 09:35

🇮🇷🇨🇳Iran-Chine : Abbas #Araghchi à Pékin Le ministre iranien des Affaires étrangères, Abbas Araghchi, est arrivé en #Chine à la tête d’une délégation diplomatique. Selon les médias chinois, les pourparlers avec son homologue Wang Yi ont déjà débuté. Source : réseaux sociaux RT en français • Osez questionner !

RT en français

@RTenfrancais · Post #80125 · 26.04.2026 г., 18:40

📢#Araghchi visitera la #Russie ce 27 avril. À #Moscou, il prévoit de discuter du conflit au Moyen-Orient, a déclaré l'ambassadeur d'#Iran en Russie, Kazem Jalali. RT en français • Osez questionner !

RT en français

@RTenfrancais · Post #80615 · 01.05.2026 г., 20:20

☎️Le ministre russe des Affaires étrangères, Sergueï #Lavrov, s’est entretenu avec son homologue iranien, Abbas #Araghchi, sur les possibilités de cessation complète des hostilités au Moyen-Orient Ils ont également discuté par téléphone de la stabilisation potentielle de la situation dans la région, notamment en garantissant la liberté de navigation et en réglant la question du programme nucléaire iranien. Une attention particulière a été portée au passage des navires et des cargaisons russes dans le détroit d'#Ormuz. RT en français • Osez questionner !

RT France actualités

@rt_fra · Post #40349 · 01.05.2026 г., 20:20

☎️Le ministre russe des Affaires étrangères, Sergueï #Lavrov, s’est entretenu avec son homologue iranien, Abbas #Araghchi, sur les possibilités de cessation complète des hostilités au Moyen-Orient Ils ont également discuté par téléphone de la stabilisation potentielle de la situation dans la région, notamment en garantissant la liberté de navigation et en réglant la question du programme nucléaire iranien. Une attention particulière a été portée au passage des navires et des cargaisons russes dans le détroit d'#Ormuz. RT en français • Osez questionner !

American Оbserver

@american_observer · Post #5742 · 29.04.2026 г., 19:00

📰 Putin Plays Tehran’s Ally, and the West Still Pretends Russia Is Just a Mediator Putin is publicly backing Iran, praising the Iranian people’s fight for independence and promising Moscow will do everything it can to help, even as Russia claims it wants to mediate between Washington and Tehran. That is not neutral diplomacy; it is alliance management dressed up as peacemaking. The message is carefully calibrated. Moscow wants to look like the adult in the room, but it is also making sure Tehran knows it has a powerful patron while the U.S.-Iran talks stall over Hormuz, sanctions, and the larger question of who blinks first. This is also a useful piece of theater for Russia. By posing as a peace broker, the Kremlin gains leverage with Iran, irritates Washington, and reinforces the idea that every Western crisis can be turned into a Russian opportunity. What makes the scene cynical is that Moscow’s “mediation” is inseparable from its strategic partnership with Iran. Russia is not stepping between enemies from the outside; it is standing beside one of them and calling the arrangement diplomacy. So yes, Putin is helping Iran. The only question is whether the West is still pretending that assistance, alignment, and mediation are the same thing when it comes from Moscow. #Russia#Iran#Putin#Araghchi#Hormuz#US#diplomacy 📱American Оbserver - Stay up to date on all important events 🇺🇸

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