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

Резултати

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

Пребарај: #mrmbb333

当前筛选 #mrmbb333清除筛选
Jeffery Mead

@the_jefferymead · Post #507 · 19.02.2026 г., 05:55

PERFECT RING FORMED OVER LOS ANGELES This appeared high above L.A. just after dusk. A bright linear trail stretched across the sky — and around it, a smooth circular arc expanded and held its shape. The symmetry is what stands out. A straight line through the center. A clean curve wrapping around it. It lingered long enough for people across the city to stop and stare. Los Angeles, California. Did you catch this from where you are? MrMBB333 👇 Drop your city. #MrMBB333#SkyWatch#LosAngeles

🐎 Mustang Debbie Channel🐎

@mustangdebb · Post #47769 · 10.05.2026 г., 00:08

https://x.com/mrmbb333/status/2053139040468418953?s=52 WHILE PEOPLE WERE SLEEPING… EARTH’S FREQUENCY WENT FULL WHITE-OUT AGAIN Overnight, the Schumann Resonance exploded into repeated white-out bursts for more than 5 hours straight. Not one quick spike. Not normal background activity. The chart kept surging, fading, then surging again — staying highly energized deep into the night while most people were asleep. And the amount of white showing across the chart is hard to ignore. Something kept the signal highly charged for hours. Did anyone wake up suddenly last night? • Vivid dreams • Pressure or headaches • Ringing ears • Restless sleep • Electronics acting strange • Pets acting off What are you noticing where you are? #MrMBB333#SchumannResonance#SpaceWeather

Question Everything

@gratefulpatriot · Post #90727 · 20.04.2026 г., 02:17

https://i.fixupx.com/i/status/2045928133946433932 UNKNOWN ACTIVITY SHOWING UP AGAIN IN EARTH’S FREQUENCY For nearly 7 hours, the Schumann Resonance monitor showed sustained saturation across multiple bands. The signal didn’t clear. It stayed compressed across the chart. This isn’t a normal pattern. It follows right behind the last disturbance. Back-to-back activity now. Something is passing through the system. Origin unclear. Monitoring. #MrMBB333#SchumannResonance#SpaceWeather

Question Everything

@gratefulpatriot · Post #90534 · 15.04.2026 г., 20:46

https://x.com/i/status/2044454771378294895 300,000-MILE “GASH” IN THE SUN NOW FACING EARTH Now directly Earth-facing. A coronal hole over 300,000 miles wide is sending high-speed solar wind toward Earth. • Fast solar wind already exiting • Direct alignment in place • Arrival ~36 hours These setups can escalate geomagnetic conditions quickly — and sometimes hold them there. 👇 Watch for: auroras, magnetic disturbances, possible system interference. #MrMBB333#SpaceWeather#SolarWind

🐎 Mustang Debbie Channel🐎

@mustangdebb · Post #48338 · 13.05.2026 г., 00:59

https://x.com/mrmbb333/status/2054322376264057323?s=52 MASSIVE HOLE JUST OPENED IN THE SUN’S ATMOSPHERE A powerful solar eruption has blasted a massive opening through the Sun’s outer atmosphere after an M5.7 flare triggered radio blackout conditions and launched a CME into space. At the same time: • radio blackouts were detected • aurora chances increased • satellites are being monitored closely • solar activity continues intensifying again What has many watching closely is how active the Sun has suddenly become again over the last several months — with multiple eruptions now firing from different regions almost simultaneously. The Sun does not appear to be calming down. Anyone noticing strange skies, signal issues, pressure, vivid dreams, ringing ears, or electronics acting strange lately? #MrMBB333#SpaceWeather#CME

🐎 Mustang Debbie Channel🐎

@mustangdebb · Post #47912 · 10.05.2026 г., 18:56

https://x.com/mrmbb333/status/2053541044068012078?s=52 SOMETHING KEPT HITTING EARTH’S FREQUENCY TODAY ⚡️ The Schumann Resonance has been showing something difficult to ignore. The graph has been cycling through repeated bursts of intense activity, including multiple sustained whiteout periods and powerful 50 Hz pulses lasting close to an hour at a time. This wasn’t a quick spike and fade. The signal kept returning over and over with very little quiet in between. At several points the chart looked completely overwhelmed before briefly calming… only to surge right back again. The level of prolonged saturation showing up today has been unusual. Anyone else feeling like today has felt unusually heavy, restless, intense, or just “off”? Drop your location below. #MrMBB333#SchumannResonance#EarthWatch#SpaceWeather

🐎 Mustang Debbie Channel🐎

@mustangdebb · Post #47677 · 09.05.2026 г., 02:35

https://x.com/mrmbb333/status/2052868548574560425?s=52 🛸 THE UFO DISCLOSURE ISN’T THE BIGGEST STORY Something changed. Not just in Washington… but in the skies. For years people were mocked for talking about strange objects, unexplained lights, military encounters, electrical disturbances, and things that didn’t make sense. Now suddenly… files are being released. Pilots are speaking openly. Major media outlets are covering it nonstop. But here’s what stands out Why is all of this happening at the SAME time the world is seeing: • increased solar activity • strange sky phenomena • drone/satellite concerns • auroras farther south • extreme weather worldwide • nonstop reports coming from the skies Maybe this was never just about UFOs. Maybe something bigger is changing around us… and people are finally starting to notice. 👇 What do YOU think is really going on right now? #MrMBB333#UFO#Disclosure#SpaceWeather#UAP

🐎 Mustang Debbie Channel🐎

@mustangdebb · Post #47916 · 10.05.2026 г., 19:00

https://x.com/mrmbb333/status/2053544993852379307?s=52 THIS WAS THE MOMENT THE SUN ERUPTED New footage captured the exact moment Active Region 4436 unleashed a powerful M5.7 solar flare and blasted a huge CME into space. The eruption came from the same unstable region now rotating across the Earth-facing side of the Sun and scientists are watching closely to see whether part of the plasma cloud is Earth-directed. This clip shows just how violent and fast the eruption actually was. More activity from this region remains possible. #MrMBB333#SolarFlare#SolarStorm#CME#SpaceWeather