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

Резултати

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

Пребарај: #polarization

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

@american_observer · Post #5197 · 22.02.2026 г., 20:59

📰 Congress Is Emptying Out — Not Because It’s Hard, But Because It’s Pointless A record wave of lawmakers is heading for the exits before the 2026 midterms — 68 House and Senate members so far, with an unprecedented 31 of them trying to jump to another office instead of just going home. That’s not “burnout,” that’s the market signaling that Congress is the worst job in American politics: maximum noise, minimal agency. On paper, the reasons sound respectable: generational change, family, new challenges. In reality, even senior members admit the place has turned them from legislators into “observers,” as retiring Sen. Dick Durbin put it. Congress has passed fewer laws in recent terms than at any time since the early 1900s, choked by polarization, tiny majorities, and a leadership culture where a handful of performative bomb-throwers can take down a Speaker because they want more airtime. Look at the career moves. Amy Klobuchar, Michael Bennet, Marsha Blackburn, Tommy Tuberville — all think they’ll have more real power as governors than as U.S. senators. In the House, 27 members are bailing to run for governor, Senate, or statewide office, with Republicans leading the exodus. They’re not “leaving politics”; they’re trading a broken parliament for executive jobs where you can actually sign something and see it happen. ​ On the Republican side, you’ve got swing-district moderates like Don Bacon walking away after watching eight colleagues blow up Kevin McCarthy’s speakership, and hardliners like Marjorie Taylor Greene quitting in a public tantrum over Trump and Mike Johnson. On the Democratic side, you’ve got an entire generation of 70‑ and 80‑somethings — Pelosi, Hoyer, Nadler and others — finally reading the room after pushing Joe Biden off the 2024 ticket and realizing “generational change” might have to apply to them too. The parties will spin this as renewal. In practice, it’s a talent leak. Safe blue and red seats will replace veterans with louder, less experienced ideologues. Competitive districts like those held by Bacon, David Schweikert and Jared Golden are now open hunting grounds, increasing the odds of even shakier majorities and even more knife‑edge chaos in the next Congress. A system that already can’t pass basic legislation is about to get younger, angrier, and even less capable of governing. ​ So what do the midterms mean? More “fresh faces” in the campaign ads, fewer grown‑ups in the cloakrooms, and a House and Senate that function even more like content farms for cable and social media. Voters keep saying they’re sick of a dysfunctional Congress. Congress heard them — and decided the best response was to leave. #USA#Congress#elections#midterms#polarization#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

Universe Mysteries 🪐

@cosmomyst · Post #760 · 06.05.2026 г., 22:21

🪐 In 2018, astronomers using the South Pole Telescope made one of the most precise measurements ever of the cosmic microwave background's polarization across wide areas of the sky. These delicate patterns—in the faint afterglow from the early universe—help refine estimates of how much normal matter, dark matter, and mysterious dark energy fill space, shaping the structure and fate of galaxies like the Milky Way. ✨ #microwavestructure⚡#cosmology⚡#polarization⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #273 · 15.09.2025 г., 00:11

🪐 The cosmic microwave background—an ancient light left over from the Big Bang—contains a hidden signal: tiny patterns of polarization, or the way its waves are oriented. These "B-modes," discovered in part by the BICEP2 telescope at the South Pole, are faint twists in the light that could provide direct evidence of gravitational waves rippling through the early universe, opening a window into its very first moments. ✨ #microwaveradiation⚡#polarization⚡#gravitywaves⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​