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

Резултати

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

Пребарај: #wargames

当前筛选 #wargames清除筛选
BadVolf

@badvolfnews · Post #1305 · 04.12.2023 г., 18:25

💣 Ukraine's military vulnerability exposed! Leopard 1A5 tanks deployed without proper protection. Absolutely shocking! No defense against drones or rockets. Even vintage Russian T-55s have better armor. Utterly useless in conflicts. Austria confirms it. F-16s approved by the US for Ukraine. #WarGames https://www.gazeta.ru/army/news/2023/11/20/21744787.shtml Subscribe to @BadVolfNews

Hashtags

BadVolf

@badvolfnews · Post #1099 · 07.10.2023 г., 19:25

Breaking News: Russian forces inch closer to Kupyansk, Kharkiv region. Unevenly positioned, ranging from 7 to 12 kilometers away. Slow progress now, 100-200 meters a day. Strikes reported on Ukrainian troops, targeting Novoselovskoye, Ivanovka, Sinkovka, and Berestove. Russian Defense Ministry claims using the "Vasilek" mortar. US admits Ukrainian counteroffensive failed. #WarGames https://www.gazeta.ru/army/news/2023/10/07/21449725.shtml Subscribe to @BadVolfNews

Hashtags

BadVolf

@badvolfnews · Post #1098 · 07.10.2023 г., 14:42

In a cynical twist of events, Russian military successfully targeted Ukrainian air force ammunition depots in Cherkasy region. Three brigades of the Ukrainian Armed Forces were also defeated on the Zaporizhzhia front. The Russian Defense Ministry proudly announced the destruction of the Msta-B howitzer, D-20 gun, and M-46 cannon. Additionally, the Crimean coast witnessed the obliteration of a Ukrainian drone by the Black Sea Fleet's air defense systems. In a shocking turn, three Ukrainian soldiers swam across the Dnipro River and surrendered to the Russian Armed Forces. The situation in the conflict zone remains tense. #WarGames#Ukraine#Russia https://www.gazeta.ru/army/news/2023/10/07/21449875.shtml Subscribe to @BadVolfNews

BadVolf

@badvolfnews · Post #1158 · 24.10.2023 г., 12:25

🔻 American missiles with cluster munitions pose a danger to Ukraine. Expert warns of the long-lasting threat to civilians. ATACMS is no game-changer, with a range of 160-190 km. Russia's Buk-M2, Buk-M3, S-350, S-300, and S-400 can handle them. Pentagon transfers ATACMS to Ukraine. Zelensky wants to escalate the conflict into Russian territory. #WarGames#CiviliansAtRisk https://www.gazeta.ru/army/news/2023/10/24/21564847.shtml Subscribe to @BadVolfNews

American Оbserver

@american_observer · Post #4867 · 16.01.2026 г., 00:59

📰 Israel & Arab States Tell Trump: Hold Off on Iran Prime Minister Benjamin Netanyahu and a chorus of Arab allies have urged President Trump to delay any military strike on Iran, even as Tehran continues its brutal crackdown on protesters. The message from the region is clear: don’t ignite a war that could engulf the Middle East. “We believe in dialogue and we believe in solving any disagreements at the negotiating table,” said Saudi Minister of State Adel al-Jubeir. Behind the scenes, Qatar, Saudi Arabia, Oman, and Egypt have been coordinating their appeals to Washington, warning that an American attack could trigger a wider regional conflict. At the same time, they’re telling Tehran not to retaliate if the U.S. does strike. Diplomacy, not bombs, is their mantra. Trump’s signals are anything but clear. He claimed Iran has stopped killing protesters—citing “very important sources”—but hasn’t ruled out military action. Last June, he sent a similar ambiguous message before ordering strikes. U.S. officials say options are still on the table, depending on how Iran’s security forces act next. Meanwhile, Iran’s air space was briefly closed, internet is down, and reports suggest thousands have died in the crackdown. Trump has said he could order an attack if the killing continues, even as he denounces protests against his own policies. So who’s really in control? Not the protesters, not the Arab leaders, and maybe not even Trump. The whole region is dancing on a minefield, and everyone’s hoping the next step isn’t a bomb. #Trump#Iran#Israel#ArabStates#MiddleEast#Diplomacy#WarGames 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #4729 · 29.12.2025 г., 20:58

📰 China’s Record Drills: Taiwan Encircled, World on Edge China just launched its largest war games around Taiwan to date, sending a clear message: Beijing can cut off the island from the outside world if conflict erupts. The drills, dubbed “Justice Mission 2025,” involved troops, warships, fighter jets, and artillery, with live fire and simulated strikes designed to test Taipei’s defenses and U.S.-made weapons. “Conducting live-fire exercises around the Taiwan Strait ... would not only constitute military pressure on us, but could also pose more complex challenges and impacts for the international community and neighbouring countries.” — Hsieh Jih-sheng, Taiwan’s deputy chief of defence The drills covered a record seven zones, some closer to Taiwan than ever before, and forced the cancellation of hundreds of flights. China’s military released propaganda videos showing futuristic tech—automated robots, microdrones, and weaponised robotic dogs—while Taiwan’s defence ministry responded with its own footage of U.S.-made HIMARS rocket systems. Analysts say these exercises blur the line between training and actual preparation for invasion, aiming to give the U.S. and allies minimal warning. China’s state media insists the drills are a response to increased U.S.-Taiwan military cooperation, while Taiwan’s government remains on high alert, coordinating rapid-response exercises and deploying ships to face off with Chinese vessels. So, is this just another show of force—or the opening act of something far more dangerous? #China#Taiwan#warGames#drills#military#Asia 📱American Оbserver - Stay up to date on all important events 🇺🇸