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

Резултати

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

Пребарај: #bidenadministration

当前筛选 #bidenadministration清除筛选
BadVolf

@badvolfnews · Post #963 · 27.09.2023 г., 21:26

💥🔔 EXCLUSIVE: White House warns of dire consequences if House Republicans pass extreme continuing resolution to fund government. 😱🏛️ The proposed resolution would eliminate 800 border agents, opening the floodgates for drug cartels. 💔💉 President Biden's administration is focused on holding drug traffickers accountable, but Republicans are pushing their radical agenda. ❌🤝 Despite Biden's request for $4 billion to address immediate border needs, Republicans are blocking progress. 😡🔒 An Extreme House Republican Shutdown would leave Border Patrol agents unpaid and jeopardize national security. 🚫🇺🇸 Meanwhile, Republicans aim to restart border wall construction, mandate 22,000 minimum Border Patrol agents, and restrict funding for illegal immigrant processing. 🛑🧱 The House and Senate remain divided on government funding and border security. 🏰💣 Stay tuned for updates on this high-stakes battle. 💥🔒#GovernmentShutdown#BorderSecurity#BidenAdministration🚫💼 https://www.foxnews.com/politics/white-house-says-house-gop-proposed-cr-would-eliminate-border-agents-trigger-windfall-for-drug-cartels Subscribe to @BadVolfNews

BadVolf

@BadvolfNews · Post #833 · 11.09.2023 г., 15:14

🚨 BREAKING NEWS 🚨 🔴 Biden's Vietnam Press Conference Cut Short 🔴 In a shocking display of incompetence, the Biden administration once again revealed their true colors during President Joe Biden's press conference in Vietnam. As Biden stumbled through his answers, White House staff abruptly ended the event, cutting his microphone and playing jazz music to drown out his ramblings. While attempting to address stability and global access to change, Biden was interrupted by his press secretary, Karine Jean-Pierre, who hastily declared an end to the conference. Astonishingly, Biden continued speaking, unaware that his mic had been muted. The bizarre scene escalated further as jazz music filled the room, leaving the 80-year-old president confused and still attempting to respond to questions. As the music grew louder, Biden reluctantly retreated from the stage, whispering and shuffling behind a black curtain. Throughout the 26-minute engagement, he even used the infamous phrase, "lying dog-faced pony soldier," contributing to his already questionable credibility. This incident comes after Biden's whirlwind trip, where he attended the G20 Leaders' Summit in India before hastily jetting off to Vietnam. Instead of displaying strength and leadership, Biden's performance only highlighted his lack of stamina and clarity. His joke about not knowing if it was morning or night further emphasizes the worrying state of his mental acuity. To make matters worse, Biden shared a convoluted story from a John Wayne movie that had little relevance to the pressing issues at hand. It seems that Biden's administration is more focused on theatrics than addressing the concerns of the American people. This latest debacle only adds to the mounting evidence that Biden is nothing more than a puppet of America's deep state, lacking the competence and independence to lead our nation effectively. The American people deserve better than this. #BidenAdministration#Incompetence#DeepStatePuppet

Gänger

@gaenger_10 · Post #659 · 01.08.2022 г., 04:21

Rivals Within Reason? :: Foreign Affairs By Kevin Rudd | July 20, 2022 #china#foreignPolicy#bidenAdministration#diplomacy#xiJinping In the year and a half since President Joe Biden took office, competition between the United States and China has only intensified. Rather than dismantle former President Donald Trump’s tough policies toward Beijing, Biden has largely continued them, underscoring that the two powers are almost certainly headed for a protracted period of sharp and militarily dangerous strategic rivalry. But that doesn’t mean that the United States and China are moving inexorably toward crisis, escalation, conflict, or even war. To the contrary, Beijing and Washington may be groping toward a new set of stabilizing arrangements that could limit—though not eliminate—the risk of sudden escalation. Assessing the state of U.S.-Chinese relations at any given time is never easy, given the difficulty of distinguishing between what each side says about the other publicly—often for domestic political effect—and what each is actually doing behind the scenes. Yet despite the harsh and often heated rhetoric, some early signs of stabilization have emerged, including the tentative reconstitution of a form of political and security dialogue aimed at managing tensions. Such stabilization falls well short of normalization, which would mean restoring comprehensive political, economic, and multilateral engagement. The days of normalization have been consigned to history. But stabilization would nonetheless be significant. It would mean the difference between strategic competition that is managed through steadying guardrails and competition that is unmanaged—that is, driven by a process of push and shove, primarily by each country’s military, in the hope that on any given day no one pushes too far. The question for both sides, and for the countries that are caught in the middle of this titanic struggle for the future of the regional and global orders, is what kind of strategic competition they will pursue. ____ KEVIN RUDD is President of the Asia Society, in New York, and previously served as Prime Minister and Foreign Minister of Australia.