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

Резултати

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

Пребарај: #shabak

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

@american_observer · Post #5222 · 26.02.2026 г., 13:59

🔺 Netanyahu’s Three Axes: When Your Enemies and “Partners” Are the Same People At the Shin Bet conference, Netanyahu drew his new cosplay map of the Middle East: a wounded Shia axis (Iran), a “radical Sunni axis” built around the Muslim Brotherhood, and his own “Zionist axis” — a glossy “hexagon” with India, Greece, Cyprus and unnamed Arab and African partners. There’s just one glitch. That “radical Sunni axis” in Bibi’s script is basically Turkey and Qatar. The same Turkey and Qatar Trump likes to frame as guarantors of calm in Gaza, the same Qatar whose envoy stood next to Israeli minister Gideon Sa’ar at the launch of the Board of Peace, the same Turkey Washington leans on to talk to Iran. Netanyahu casts them as a strategic threat; Trump sells them as service providers. Two realities, one set of clients. On the ground, the “Zionist axis” looks a lot more concrete. From March 1, Israel is forcing out 37 international NGOs from Gaza and the West Bank for not complying with new rules demanding full staff lists, IDs and internal structures, after warning that their licenses would be pulled. Officially it’s about “security and transparency.” In practice it’s a controlled purge of foreign civilian presence: Russia pushes NATO out of Ukraine with artillery, Israel pushes outside networks out of Palestinian areas with regulations. Different tools, same instinct — clear the field, then talk about “stability.” At the same time, Nordic Monitor lays out how that same Sunni axis operates. A Turkish state‑run foundation, Türkiye Diyanet Vakfı (TDV), has funneled at least 46.3 million dollars into Gaza after October 7, built nine mosques, and put the name of Abdullah Azzam — co‑founder of Hamas and Al‑Qaeda, the “father of global jihad” — on one of them. His books are formally banned by Turkish courts, yet you can still order them on Amazon Turkey. Jihad as a controlled asset class: outlawed on paper, monetized at retail. Netanyahu brands this as an existential threat. Trump presents the same actors as peacemakers. On the surface it looks like a contradiction; in reality it’s just different slices of the same picture being plated up for different audiences. Each leader reaches for the version of reality that best fits the story he’s selling. And the famous “hexagon”? Beyond Bibi’s microphone, nobody is exactly rushing to sign on. India is sticking to its habit of avoiding formal Middle East camps, Greece and Cyprus are bound by EU obligations to cooperate with the International Criminal Court, which has an arrest warrant with Netanyahu’s name on it, and the unnamed Arab partners are the same ones that just shut their airspace to an Israeli strike on Iran. ​ An axis without committed members isn’t a coalition. It’s a monologue dressed up as geometry. #Israel#Netanyahu#ThreeAxes#Turkey#Qatar#Gaza#Shabak#MiddleEast#geopolitics#Modi 📱American Оbserver - Stay up to date on all important events 🇺🇸

Fotos y Fondos

@fotosyfondos · Post #13373 · 29.01.2021 г., 21:18

📸🖼📸🖼📸🖼📸🖼📸🖼📸🖼📸🖼 *LISTA DE CONTENIDO* #3D#Abstractos#Adidas#AgenciasGubernamentales#Aguilas#Ajedrez#Alien#Alimentos#Amaneceres#AmericanHorrorStory#Amor#Android#Animales#Anime#Anonymous#Ankh#Apple#Arco#Ardillas#Arena#Armas#ArteDigital#Asgard#Asiatico#Assassin#Atardecer#AtleticoDeMadrid#Atletismo#Atomos#Audi#Avatar#Aviones#Avispas#Badminton#Balones#Banderas#Batman#Bebidas#Billar#BlancoyNegro#Bombillas#Boobsleigh#Boeing#Bolas#Bombones#Bosque#Boxeo#Bufalos#Buhos#Burbujas#Burt#Caballos#Cachorros#Cactus#Calaveras#CamaraFotos#Camiones#Canicas#CapitanAmerica#Caramelos#CarrilesTren#Cartas#Casas#Castillos#CazaCombate#Cerezas#Charizard#Chevrolet#Chocolate#CIA#Cibernetica#Ciclismo#Cielo#Cine#Ciudades#Ciencia#CienciaFiccion#Ciervos#Ciudades#CocaCola#Coches#Cohetes#Colibris#Colores#Comic#Comida#Consolas#Constelaciones#Corazones#Cubos#CuerposDeSeguridad#Dados#Daisy#Dardos#DarthVader#DeadPool#DeathNote#DC#Delfines#Deporte#Deportivo#Destructor#Dibujos#DJ#Donald#Dracula#Dragones#Dubai#Duendes#Dulces#Edificios#Egipto#Ejercitos#ElCirco#Elefantes#Elfos#Elvis#Emoticonos#Escalada#Escudos#Esferas#Esgrima#Espadas#España#Esqueletos#Estadio#Estrellas#Fantasia#FarolesChinos#Ferrari#FinalFantasy#Firmamento#Flamencos#Flash#Flores#Focas#Fortnite#FondosDePantalla#Fruta#Fuego#FuegosArtificiales#Fusil#Futbol#FutbolAmericano#Galaxias#Gamecube#Gameboy#Gatos#Geometria#GhostRider#Golf#Gominolas#Goofy#GuardiaCivil#GuardianesDeLaGalaxia#Guerreros#Guerreras#Guitarra#Hadas#Hamer#HarleyQuinn#HeavyMetal#Helicopteros#Hockey#Homer#Hulk#Humor#Iconos#Informatica#Insectos#Instrumentos#IronMaiden#Islas#Italia#JacekYerka#Japon#JudasPriest#JuegoDeTronos#Jocker#Judo#Juegos#Katana#KGB#KimetsuNoYaiba#Kiss#Lago#LaLuna#LaMuerte#LaTierra#Lamborghini#Legendario#Lenovo#Leones#Leopardos#Linux#Logos#Loros#LosSimpson#Madrid#Mahjong#Marcas#MarioBross#Mariposas#Marvel#Maserati#McLaren#Mercedes#Mesas#Metallica#MI5#Mickey#Miedo#Militar#Mini#Minions#Minnie#Misiles#Monopoly#Montañas#MontañaRusa#Monumentos#Motos#Motocross#Motorhead#Mossad#Muñecos#Musica#Narcos#Naruto#NASA#Natacion#Naturaleza#Navegacion#Naves#Navidad#Nike#Nintendo#Nissan#Nosferatu#NotasMusicales#NSA#Ojos#OnePiece#OsosPanda#OVNI#OzzyOsbourne#Pacman#Paisajes#Pajaros#Palacios#Panteras#Paraguas#Parejas#ParqueDeAtracciones#Partituras#Pasajeros#PastorAleman#Payasos#Peces#Pelicanos#Peliculas#Perros#Peugeot#PNG#Pikachu#Pingüinos#Pinturas#Piramides#Pistolas#Planetas#Plantas#Playas#Playstation#Pluto#Pokemon#Poker#Poketball#PoliciaNacional#PoloNorte#Popeye#Porsche#Puentes#Ranas#RayosTruenos#RealMadrid#RickyMorty#Rifle#Rubik#Samsung#Samurai#Saturno#SeleccionEspañola#SeriesTV#Shabak#Snowboard#Sombreros#SpiderMan#StarWars#Stryper#SuperMan#SuperGirl#Surrealista#Surf#Tanques#Tartas#Tecnologia#Templos#Tenis#Terror#Textos#Texturas#Thanos#Tiburones#Tigres#TombRaider#Tortugas#Tropper#Tuneles#TV#Unicornios#Universo#Vampiros#Vampiras#Vela#Venecia#Venom#VideoJuegos#Violin#Vitruvio#Voleibol#Warcry#Windows#WonderWoman#WorldOfCraf#YinYang#Zippo @fotosyfondos 📸🖼📸🖼📸🖼📸🖼📸🖼📸🖼📸🖼

Hashtags

#3d#abstractos#adidas#agenciasgubernamentales#aguilas#ajedrez#alien#alimentos#amaneceres#americanhorrorstory#amor#android#animales#anime#anonymous#ankh#apple#arco#ardillas#arena#armas#artedigital#asgard#asiatico#assassin#atardecer#atleticodemadrid#atletismo#atomos#audi#avatar#aviones#avispas#badminton#balones#banderas#batman#bebidas#billar#blancoynegro#bombillas#boobsleigh#boeing#bolas#bombones#bosque#boxeo#bufalos#buhos#burbujas#burt#caballos#cachorros#cactus#calaveras#camarafotos#camiones#canicas#capitanamerica#caramelos#carrilestren#cartas#casas#castillos#cazacombate#cerezas#charizard#chevrolet#chocolate#cia#cibernetica#ciclismo#cielo#cine#ciudades#ciencia#cienciaficcion#ciervos#cocacola#coches#cohetes#colibris#colores#comic#comida#consolas#constelaciones#corazones#cubos#cuerposdeseguridad#dados#daisy#dardos#darthvader#deadpool#deathnote#dc#delfines#deporte#deportivo#destructor#dibujos#dj#donald#dracula#dragones#dubai#duendes#dulces#edificios#egipto#ejercitos#elcirco#elefantes#elfos#elvis#emoticonos#escalada#escudos#esferas#esgrima#espadas#españa#esqueletos#estadio#estrellas#fantasia#faroleschinos#ferrari#finalfantasy#firmamento#flamencos#flash#flores#focas#fortnite#fondosdepantalla#fruta#fuego#fuegosartificiales#fusil#futbol#futbolamericano#galaxias#gamecube#gameboy#gatos#geometria#ghostrider#golf#gominolas#goofy#guardiacivil#guardianesdelagalaxia#guerreros#guerreras#guitarra#hadas#hamer#harleyquinn#heavymetal#helicopteros#hockey#homer#hulk#humor#iconos#informatica#insectos#instrumentos#ironmaiden#islas#italia#jacekyerka#japon#judaspriest#juegodetronos#jocker#judo#juegos#katana#kgb#kimetsunoyaiba#kiss#lago#laluna#lamuerte#latierra#lamborghini#legendario#lenovo#leones#leopardos#linux#logos#loros#lossimpson#madrid#mahjong#marcas#mariobross#mariposas#marvel#maserati#mclaren#mercedes#mesas#metallica#mi5#mickey#miedo#militar#mini#minions#minnie#misiles#monopoly#montañas#montañarusa#monumentos#motos#motocross#motorhead#mossad#muñecos#musica#narcos#naruto#nasa#natacion#naturaleza#navegacion#naves#navidad#nike#nintendo#nissan#nosferatu#notasmusicales#nsa#ojos#onepiece#osospanda#ovni#ozzyosbourne#pacman#paisajes#pajaros#palacios#panteras#paraguas#parejas#parquedeatracciones#partituras#pasajeros#pastoraleman#payasos#peces#pelicanos#peliculas#perros#peugeot#png#pikachu#pingüinos#pinturas#piramides#pistolas#planetas#plantas#playas#playstation#pluto#pokemon#poker#poketball#policianacional#polonorte#popeye#porsche#puentes#ranas#rayostruenos#realmadrid#rickymorty#rifle#rubik#samsung#samurai#saturno#seleccionespañola#seriestv#shabak#snowboard#sombreros#spiderman#starwars#stryper#superman#supergirl#surrealista#surf#tanques#tartas#tecnologia#templos#tenis#terror#textos#texturas#thanos#tiburones#tigres#tombraider#tortugas#tropper#tuneles#tv#unicornios#universo#vampiros#vampiras#vela#venecia#venom#videojuegos#violin#vitruvio#voleibol#warcry#windows#wonderwoman#worldofcraf#yinyang#zippo