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

Резултати

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

Пребарај: #bardella

当前筛选 #bardella清除筛选
Ultimora.net - POLITICS

@UltimoraPOlitics · Post #39273 · 11.05.2022 г., 18:30

#Francia Jordan #Bardella (#RN|ID): "Bisogna bloccare con solennità e serietà l'unione di estrema sinistra e antirepubblicana. Un blocco di 50 sfumature di rosso che non ha più alcun complesso per fare un patto con l'Islam politico e l'indigenismo. Abbiamo deciso di candidare 569 figure, di cui 289 uomini e 280 donne." @UltimoraPolitics

Ultimora.net - POLITICS

@ULTIMORAPOLITICS · Post #44882 · 09.06.2024 г., 19:31

#Francia🇫🇷, Marine #LePen: “Siamo pronti a prendere il potere. Il voto dei francesi è definitivo: il presidente, rispondendo all'appello di Jordan #Bardella, ha appena annunciato il ritorno dei francesi alle urne tra poche settimane. Siamo pronti a esercitare il potere, pronti a porre fine a questa immigrazione di massa, a fare del potere d’acquisto una priorità, pronti a rilanciare la Francia” - Agi @UltimoraPolitics

Ultimora.net - POLITICS 24

@Ultimorapolitics24 · Post #51632 · 09.01.2026 г., 17:52

🇫🇷 Jordan #Bardella ha annunciato su X che il Rassemblement National presenterà due mozioni di censura: una all'Assemblea nazionale contro il governo e una al Parlamento europeo contro la Commissione von der #Leyen, in merito all'accordo UE-Mercosur. @UltimoraPolitics24

RT en français

@RTenfrancais · Post #80683 · 02.05.2026 г., 17:20

🔵#Bardella critique la politique économique du gouvernement Le président du Rassemblement national, Jordan Bardella, a critiqué la politique économique d'Emmanuel #Macron, accusant son gouvernement d'entraîner le déclin industriel, de fragiliser les travailleurs et d'accroître la dépendance économique de la #France. Crédit vidéo : Rassemblement national RT en français • Osez questionner !

RT France actualités

@rt_fra · Post #40417 · 02.05.2026 г., 17:20

🔵#Bardella critique la politique économique du gouvernement Le président du Rassemblement national, Jordan Bardella, a critiqué la politique économique d'Emmanuel #Macron, accusant son gouvernement d'entraîner le déclin industriel, de fragiliser les travailleurs et d'accroître la dépendance économique de la #France. Crédit vidéo : Rassemblement national RT en français • Osez questionner !

American Оbserver

@american_observer · Post #5348 · 11.03.2026 г., 00:00

📰 Perpignan Inc.: Law, Order and Overdraft Perpignan is the National Rally’s demo version of France: more cops, more cameras, more debt, and a mayor who might be legally disqualified before he can finish bragging about it. Louis Aliot sells the city as a “laboratory” of far-right governance — security as the core product, municipal politics as a test bench for 2027. On the metrics he chose, he delivers: municipal police up from 161 to 199 officers, 1.6 local cops per 1,000 residents — the highest ratio among big French cities and nearly triple Paris — plus plans for 50 more officers and 200 extra cameras, especially in poor, heavily North African and Roma neighborhoods. Drug-trafficking cases and fines explode, crime stats go up, and RN spins that as proof it’s finally “doing something” about the violence it talks about nonstop. The bill arrives quietly: debt per resident is far above comparable cities, property and business taxes are higher than in most peers, and opponents say the PR machine is the only thing truly overperforming. Yet Aliot still leads in the polls, Marine Le Pen and Jordan Bardella use Perpignan as a backdrop to promise “public order as an absolute priority,” and even skeptical voters admit they feel the streets look cleaner — then add they don’t buy the rest of the program. This is the far-right offer in one city: turn poverty and neglect into a permanent crime scene, flood it with police, send the bill to taxpayers, and call the whole thing “responsibility.” If it works in Perpignan, they’ll scale it — not because it fixes anything, but because fear and fines still poll better than admitting you have no answer for why the city was abandoned in the first place. #france#perpignan#Aliot#LePen#Bardella#farRight#security#police#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

Ultimora.net - POLITICS 24

@Ultimorapolitics24 · Post #52197 · 16.03.2026 г., 13:49

🇫🇷#Francia — Ieri si è votato per le elezioni amministrative: male i candidati macronisti, bene invece i socialisti, la sinistra di #Melenchon e la destra di #Bardella. A Parigi sarà ballottaggio tra il socialista Emmanuel #Gregoire e l’ex ministra Rachida #Dati, vicina a Macron e al centrodestra. A Marsiglia si sfideranno il sindaco uscente di sinistra Benoît #Payan e il candidato di #RN, Franck #Allisio. I Verdi prevalgono a Lione, a Lille ci sarà un ballottaggio tra sinistra e centrosinistra, mentre l’ex premier centrista #Philippe è in testa a Le Havre. Il centrosinistra arriva primo anche a Strasburgo, Rennes, Nantes e Bordeaux. Il #RN ha vinto al primo turno a Perpignan e punta a governare diverse città della Costa Azzurra, come Marsiglia, Tolone e Nizza. I ballottaggi si terranno il 22 marzo. @UltimoraPolitics24