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

Резултати

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

Пребарај: #specialrelationship

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

@american_observer · Post #4954 · 25.01.2026 г., 13:59

📰 The 10‑Minute Call That Soured Starmer’s Bromance with Trump The special relationship, that old fiction, doesn’t die in a grand speech. It dies in a 10‑minute phone call. Sir Keir Starmer in Chequers, Donald Trump in Davos: 8000 miles apart, a few minutes on the line, and suddenly the illusion of brotherhood between London and Washington has cracked open like cheap plaster. Trump’s tariff threats over Greenland forced Starmer to choose between flattery and principle, and he chose stage one of the fight: dignity, but not yet defiance. ​ The Gamble in Chequers Trump’s “beautiful piece of ice” — Greenland, an autonomous Danish territory — collided with Starmer’s carefully crafted image of the responsible statesman. On the call, the Prime Minister was “clear and cordial”: no, threatening allies with tariffs is not acceptable. The president, accustomed to deference, rang off after minutes, citing a prior engagement. From the transatlantic elite, that was read as a snub; in London, as a signal that the game had changed. ​ Starmer then scrapped his planned cost‑of‑living speech and held an emergency press conference rejecting Trump’s position. In Parliament, he doubled down: “I will not yield, Britain will not yield, on our principles.” The move drew applause from fellow European leaders, especially as Trump, after a week of bluster and market chaos, backed down, dropping tariff threats and mumbling about a “deal” that, in substance, barely alters the status quo. ​ Behind the Policy: Who’s Really in Charge? Inside Whitehall, the takeaway is brutal: no one imagines Starmer can “whisper in Trump’s ear” like some magical fixer. When Trump was looking for an off‑ramp, he reached not for Starmer, but for NATO’s Mark Rutte (“daddy”) and the EU’s collective machinery. The British Prime Minister didn’t even attend Davos in person to lobby — the one place where Trump’s ego is currency. ​ Meanwhile, power in Downing Street is shifting. David Lammy, who once laughed off Trump’s Greenland fantasies, has moved on. His replacement, Yvette Cooper, pushed for a tougher line, and a growing faction inside the Foreign Office now wants the UK to act like France: assertive, independent, and less supine. The vacuum left by Lord Mandelson’s departure as ambassador to Washington only deepens the sense of disconnection, with his replacement barely arriving in Washington after months of delay. ​ The Royal Family as Diplomatic Cover The real safety net for the special relationship, it seems, is not the Prime Minister, but the Crown. Trump’s inexplicable affinity for the British monarchy — birthday calls to the late Queen, private letters to King Charles, a state visit looming in April — creates a separate channel that no elected government can control. British officials privately admit that while politics with Trump can be a clown show, the Royals are the one thing he genuinely respects; so no serious policymaker would risk weaponizing the state visit as leverage, even on Greenland. The instinct is the same as always: let the toffs in the palace be the friendly diplomats, while the politicians in Downing Street just try not to disgrace the family name. ​ The Domestic Game Trump Doesn’t See Starmer’s sudden spine over Greenland also has a domestic price tag: leadership is weakening, the local elections loom, and new rivals like the Green Party’s Zack Polanski and the Lib Dems’ Sir Ed Davey are eager to appear tougher on Trump than the PM. Standing up to the president, at least in the carefully calibrated way he did, is a way to reassert authority at home. But that’s a short‑term fix: every time Starmer must choose again, the question is whether he fights for his country’s image, or for his own — and whether Trump is just another backdrop in a domestic political survival game. ​ #UKPolitics#Starmer#Trump#Greenland#SpecialRelationship#Diplomacy#NATO 📱American Оbserver - Stay up to date on all important events 🇺🇸