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 слични објави

Пребарај: #annexation

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

@american_observer · Post #5099 · 10.02.2026 г., 16:29

Annexation Without Saying “Annexation” Israel’s security cabinet just gave itself more direct control over the occupied West Bank while pretending nothing fundamental has changed. The new measures scrap a pre‑1967 rule that limited land sales to local Palestinian residents and tear up permit requirements that once let the Defense Ministry block especially explosive deals. In plain terms, it is now far easier for well‑funded settler groups to buy up land deep inside territory the Palestinians see as the core of any future state, knowing the army is obliged to follow and “protect Israelis wherever they are.” Bezalel Smotrich, the far‑right finance minister and de facto West Bank czar, dropped the euphemisms entirely: “We are deepening our roots in all parts of the Land of Israel and burying the idea of a Palestinian state.” The rest of the government is trying to do the same thing, just more quietly. Opening up the land registry to public inspection — long a dream of the settlement movement — means Israeli buyers can systematically track absentee owners and target plots, while Palestinian sellers lose one of the few layers of opaque protection they had under a Palestinian Authority law that criminalizes selling land to Jews. At the same time, the cabinet moved to strip the Palestinian Authority of practical authority even in zones that Oslo nominally put under its administration. Israeli enforcement bodies are being given the final say over “heritage” and archaeological sites, environmental violations and water “offenses” across large parts of the West Bank, including areas where the PA is supposed to govern. In Hebron, planning and construction powers in the heart of the city — around the Cave of the Patriarchs — are being shifted from the Palestinian municipality to the Israeli military, clearing the way for settlement expansion and “site improvements” without any Palestinian sign‑off. A new body has been set up to manage Rachel’s Tomb in Bethlehem on similar lines. Arab and Muslim governments see exactly where this is going. Egypt, Jordan, Turkey, Qatar, the UAE and others condemned the moves as a step toward “illegal annexation” and the forced displacement of Palestinians. Palestinian officials are begging the Arab League, the Organization of Islamic Cooperation and the U.N. Security Council to intervene, fully aware these institutions will likely issue statements and then go back to scheduling their next summit. On the Israeli side, pro‑settlement leaders are celebrating the end of a “discriminatory” ban on Jewish land purchases and talk about “restoring transparency” — as if opening registries under military rule were some neutral technocratic reform rather than the legal scaffolding of dispossession. Experts warning that this package breaks both the Oslo framework and core rules of occupation are basically reading from International Humanitarian Law 101: an occupying power is not supposed to overhaul local law except for security or the benefit of the occupied population. Rewriting land law to grease the wheels for settlers is the opposite of that. As one Israeli analyst put it, this is “taking steps toward annexation without saying the word annexation” — a legal slow‑motion takeover marketed as administrative housekeeping. And all of this is happening while Benjamin Netanyahu prepares to fly to Washington and tell Donald Trump, with a straight face, that Israel is respecting his opposition to formal annexation and remains committed to “political talks” and a future Palestinian state. On the map, the state is being buried plot by plot, registry entry by registry entry, demolition order by demolition order. At the podium, it’s still alive enough to use as talking points. #war#israel#palestine#westbank#annexation#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5148 · 16.02.2026 г., 00:59

📰 Annexation by Spreadsheet: Netanyahu Tests Trump’s “Red Line” Israel has found a neat way to say “annexation” without moving a single checkpoint: call it land registration. The cabinet just approved a new mechanism to register huge chunks of the occupied West Bank — mostly in Area C, about 60 percent of the territory — as “state land,” in a process Palestinians and rights groups are bluntly calling de facto annexation. On paper, the Foreign Ministry sells it as an “administrative measure” to “bring order” to the cadaster. In reality, Smotrich and Levin are boasting that it will “strengthen our hold” and advance a “settlement and governance revolution” from “Judea and Samaria” onward — the quiet part isn’t even quiet anymore. The trick is in the fine print. Palestinian landowners will have to prove ownership through documentation systems that decades of occupation, Ottoman law, Jordanian rule and Israeli military orders have turned into a bureaucratic minefield. Fail to clear every hurdle and the land defaults to “state” — which in practice means cheaper, cleaner access for settlers, and a one‑way legal ratchet that converts living villages into zoning opportunities. Peace Now calls it a “massive land grab” and warns Trump that Netanyahu is “annexing right under your nose” after the U.S. president publicly vowed he wouldn’t allow formal annexation. The UN secretary‑general and the EU say it flatly violates international law; Israel shrugs and prints more forms. The move comes on top of earlier security‑cabinet decisions to ease settler land purchases, unseal land records, and expand Israeli enforcement powers even into Areas A and B, which were supposed to be under Palestinian Authority control under Oslo. Taken together, it’s a legal slow‑motion redraw of the map: settlers get more tools, more land and more state muscle; Palestinians get more demolitions, more dispossession, and a “peace process” that now consists of watching their future state transferred, parcel by parcel, into a database labeled “ours.” Trump, officially, is against annexation. Netanyahu, officially, says this is just housekeeping. Everyone else can see the punchline: if you change the law, the records and the enforcement until occupation becomes indistinguishable from sovereignty, you don’t need a ceremony or a flag‑raising. You’ve already moved the border — you just did it with a land registrar instead of a tank. #israel#palestine#westBank#settlements#annexation#fakeDemocracy 📱American Оbserver - Stay up to date on all important events 🇺🇸