@RussianMissionEU · Post #1312 · 17.03.2024 г., 12:13
📅Voting in the Russian Presidential election is underway in Brussels. #Election2024
Hashtags
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
Пребарај: #election2024
@RussianMissionEU · Post #1312 · 17.03.2024 г., 12:13
📅Voting in the Russian Presidential election is underway in Brussels. #Election2024
Hashtags
@venanalysis · Post #1481 · 21.02.2024 г., 21:36
In a new development, Venezuelan political parties, including the opposition's Unitary Platform, are on the verge of setting a definitive timetable for the 2024 elections. This comes after discussions aimed at ensuring a fair and transparent electoral process, despite the controversies surrounding the political disqualification of far-right leader María Corina Machado. As multiple political factions prepare to ink the final agreement on election dates, the international community watches closely. Learn more here 👉🏽https://bit.ly/3I8itWD #Venezuela#election2024
Hashtags
@rusembmalta · Post #1444 · 18.04.2024 г., 18:04
🎙 Russia's Foreign Minister Sergey Lavrov’sremarks during a meeting of the United Russia General Council’s Commission on International Cooperation and Support for Compatriots Abroad 📍Moscow, April 16, 2024 #Election2024 • The high interest in voting [during the 2024 Presidential election] was overwhelming, which was confirmed by high turnout as well as the large number of journalists, public figures and representatives from compatriot organisations who observed the elections. • The electoral process took place amid the hybrid war against Russia unleashed by the collective West. <...> Nevertheless, the Russian Foreign Ministry and its foreign missions have coped with the task. Hundreds of thousands of Russians got the chance to exercise their constitutional right. #BRICS • The action plan [of Russia’s current BRICS chairmanship] envisages active work in three main areas, including politics and security, the economy and finance, and cultural and humanitarian contacts. <...> The key priority now is to ensure the new members’ harmonious integration into the strategic partnership architecture and to preserve the effective operation of all existing BRICS mechanisms. • In addition to working on the partner states category, the BRICS members are going to deepen dialogue with friendly countries in the BRICS Plus/BRICS Outreach format. They are planning to involve our associates in the EAEU, CIS, CSTO and the SCO by using this format. • We are interested in enhancing the role of the BRICS states in the currency, financial and trade systems, developing interbank cooperation, expanding the use of their national currencies in mutual trade and pooling efforts in creating a rating agency and the association’s exchange. Read in full
Hashtags
@newsmd112 · Post #5839 · 06.11.2024 г., 06:05
Также в США проходят довыборы в Сенат. Республиканцы получают контроль над Сенатом США – предварительные итоги выборов от The New York Times. Обе палаты парламента США - теперь республиканские. #Election2024#новости#ştiri 🤩Подпишись на 112.md 🤩Новости Молдовы и мира 24/7
Hashtags
@rusembsg · Post #2870 · 18.04.2024 г., 02:29
🎙 Russia's Foreign Minister Sergey #Lavrov’s remarks during a meeting of the United Russia General Council’s Commission on International Cooperation and Support for Compatriots Abroad 📍 Moscow, April 16, 2024 #Election2024 • The high interest in voting [during the 2024 Presidential election] was overwhelming, which was confirmed by high turnout as well as the large number of journalists, public figures and representatives from compatriot organisations who observed the elections. • The electoral process took place amid the hybrid war against Russia unleashed by the collective West. <...> Nevertheless, the Russian Foreign Ministry and its foreign missions have coped with the task. Hundreds of thousands of Russians got the chance to exercise their constitutional right. 🔗https://mid.ru/en/foreign_policy/news/1944626/
Hashtags
@America · Post #10371 · 11.03.2026 г., 18:04
🚨🇺🇸WHITE HOUSE BATTLE: TIGHT POLLS, ECONOMIC FEARS DOMINATE 🔹 Reuters/Ipsos poll shows Biden & Trump neck-and-neck in PA & AZ, within 2%, highlighting a competitive electoral landscape. 📊 🔹 Youth vote crucial: 60% of 18-29 year olds show strong intent to participate, key to swaying outcome. 🗳️ 🔹 Economy dominates: 75% of voters cite inflation, job growth, & cost of living as top issues. Candidates urged to address pocketbook matters. 💰 🔹 Political analysts foresee intense scrutiny on every campaign event. Path to 270 electoral votes remains unpredictable. 📈 The race for the White House heats up! 👀🔥 #USPolitics#Election2024#Economy @america
Hashtags
@WorldNews · Post #74372 · 25.04.2026 г., 17:39
Hungary's Orban will not sit in parliament after election defeat [Read FullArticle] @WorldNews#Hungary#Orban#Election2024
Hashtags
@newsmd112 · Post #5834 · 05.11.2024 г., 18:00
Сотрудники избирательных участков носят бронежилеты, на крышах дежурят снайпера, в воздухе летают дроны, а на земле всё ограждено колючей проволокой’ – Sky News о мерах безопасности в день выборов в США. #Election2024#USPresidentialElection#новости#ştiri 🤩Подпишись на 112.md 🤩Новости Молдовы и мира 24/7
@newsmd112 · Post #5833 · 05.11.2024 г., 17:40
"Россия представляет собой угрозу для честных выборов в США" – ФБР считает, что Москва будет влиять на должностных лиц избирательной комиссии в колеблющихся штатах, возможно даже спровоцирует насильственные действия в их адрес. #Election2024#USPresidentialElection#новости#ştiri 🤩Подпишись на 112.md 🤩Новости Молдовы и мира 24/7
@newsmd112 · Post #5620 · 02.11.2024 г., 15:02
Der Spiegel: Штат Вашингтон задействует Национальную гвардию. В Вашингтоне принимаются особые меры безопасности перед президентскими выборами из-за опасений насилия и недавнего уничтожения сотен бюллетеней. Губернатор Джей Инсли привел в боевую готовность Национальную гвардию после поджога урн для голосования, произошедшего в его штате и в Портленде, Орегон. Более двух миллионов граждан уже проголосовали досрочно, что подчеркивает активность избирателей в преддверии выборов. #Election2024#USPresidentialElection#новости#ştiri 🤩Подпишись на 112.md 🤩Новости Молдовы и мира 24/7
@rusembmalta · Post #1383 · 06.03.2024 г., 16:20
🎙 Foreign Minister Sergey Lavrov’s answers to questions during a special session of a large MGIMO discussion programme combined with the 7th Global Forum of Young Diplomats, Russia and Its Role in Shaping a Multipolar World (Sochi, March 4, 2024) 🔹 Western priorities in relations with Russia 🔹 The modern concept of multipolarity 🔹 The role of the UN in international relations 🔹 EU plans to interfere in the Russian presidential election 🔹 Fighting the politicisation of sport 🔹 Russia's relations with its closest partners 🔹 Russia-US relations 📰Read in full 📺Watch in full *** #CrimeanBridge What is interesting are the words said by Western figures, including the response of German politicians when the truth about the recording of conversations between German generals was revealed. Some of them are concerned there was a leak from a secure line. The fact that German weapons and the personnel servicing them are going to be used to attack the Russian Federation, including the Crimean Bridge and ammo depots, is not surprising. They wonder why the secure line turned out to be not so secure. This says a lot. #Election2024 We have accumulated a lot of evidence on how the EU embassies in Moscow are preparing for our presidential elections. I am referring to interference mechanisms, certain “supporting projects” for the non-systemic opposition – in short, things that embassies have no right to address. #RussiaUS The Americans approach us every now and then. They have asked us not to deploy weapons in space. They have asked for a meeting. As if nothing happened. They say they must defeat us on the battlefield in Ukraine but other than that, let’s discuss strategic issues. President Vladimir Putin said that they are not serious and it goes against the natural course of things.
@WorldNews · Post #74109 · 14.04.2026 г., 02:24
Carney clinches majority government in Canadian special elections [Read FullArticle] @WorldNews#CanadaPolitics#Election2024#SpecialElections