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

Резултати

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

Пребарај: #drugtrafficking

当前筛选 #drugtrafficking清除筛选
Venezuelanalysis

@venanalysis · Post #2086 · 02.09.2025 г., 19:10

📑🖊 OPINION | The Great Hoax Against Venezuela: Oil Geopolitics Disguised as ‘War on Drugs’ Former UN anti-drugs agency director Pino Arlacchi dismantles the “narco-state” narrative with 30 years of reliable data. The 2025 UNODC and European Drug Reports confirm Venezuela’s marginal role in global drug trafficking, with no coca cultivation or cartel presence. Arlacchi states the “Cartel de los Soles” is a political fabrication, absent from all international anti-drug reports. 👉🏽 Read the full opinion piece here: https://shorturl.at/69vho #DrugTrafficking#NicolasMaduro

Venezuelanalysis

@venanalysis · Post #2176 · 17.11.2025 г., 23:01

📰 NEWS | Venezuela: Rubio Pushes ‘Foreign Terrorist’ Designation While Trump Floats Maduro ‘Discussions’ The US will designate the alleged “Cartel de los Soles” as a Foreign Terrorist Organization on Nov. 24. Despite repeated accusations, US officials have not presented court-tested evidence tying Maduro or other Venezuelan leaders to drug trafficking. Trump has also raised the possibility of upcoming talks with the Maduro government. This comes as Washington continues a significant military buildup in the Caribbean and has carried out 22 boat strikes that resulted in 83 civilian deaths, without disclosing evidence of the vessels’ cargoes or crews. Read the full report here 👉🏾https://shorturl.at/c7RIV #DrugTrafficking#USMilitaryThreats#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #2115 · 27.09.2025 г., 13:00

📑🖊 OPINION | From WMDs to “Narco-states”: How the US Sells Wars the Intelligence Doesn’t Support Analyst Alan MacLeod exposes how Washington's growing attacks against Venezuela are built on biased and evidence-free narratives. The U.S. has escalated its military presence in the Caribbean, with 7 warships, a submarine, an amphibious assault ship, and F-35 jets deployed near Venezuela. However, UN and DEA reports contradict Washington’s claims that Venezuela is a key drug producer. 🔗 Read the full opinion piece here: https://shorturl.at/HnTkw #DrugTrafficking#USMilitaryThreats#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #2104 · 15.09.2025 г., 22:13

🎥 VIDEO | ‘All About Oil’: Breaking Down US Military Threats and Drug Trafficking Charges The Trump administration recently escalated military threats against Venezuela, citing drug trafficking as justification. On Breakthrough News, VA's José Luis Granados Ceja explained that these charges lack legal basis and reflect political motives behind Washington’s attacks. 👉 Watch the full video here: https://venezuelanalysis.com/video/all-about-oil-breaking-down-us-military-threats-and-drug-trafficking-charges/ #USVenezuelaRelations#USMilitaryThreats#DrugTrafficking

Venezuelanalysis

@venanalysis · Post #2103 · 15.09.2025 г., 16:25

📰 NEWS | Venezuela Warns US Seeks Regime-Change ‘Provocations’ After US Forces Board Fishing Boat Venezuela condemned the interception of the fishing boat Carmen Rosa by US forces, calling it an “illegal and hostile” act meant to provoke military escalation in the Caribbean. US officials said the operation occurred in international waters after a drug tip that proved false. The incident comes as Washington has deployed thousands of troops, warships, and aircraft to the region, and just weeks after a US strike on a boat near Trinidad and Tobago killed 11 people. 👉 Read the full report here: https://shorturl.at/aonpA #DrugTrafficking#USMilitaryThreats#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #2112 · 25.09.2025 г., 20:32

📰 NEWS | Venezuela’s Maduro Moves to Invoke Emergency Powers as US Doubles Down on Its Aggressive Stance Toward Latin America Venezuela is preparing to enact a State of Exterior Commotion, granting emergency powers to the executive in response to US military threats, including naval deployments and lethal strikes in the Caribbean. The Trump administration has redirected $1.8 billion in foreign aid toward a new “America First” strategy, naming Venezuela, Cuba, and Nicaragua as targets. US forces have deployed 4,500 troops, warships, and a nuclear submarine off Venezuela’s coasts. 👉🏽 Read the full report here: https://shorturl.at/8UX2T #ALBA#DrugTrafficking#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #2111 · 23.09.2025 г., 21:31

📰 NEWS | Maduro Calls for US-Venezuela Dialogue in Letter to Trump, Refutes Drug-Trafficking Claims President Maduro addressed a letter to Donald Trump calling to “preserve peace” and expressing willingness to resume dialogue through White House Envoy Richard Grenell. Maduro also rejected drug-trafficking allegations against Caracas, pointing to UN and DEA reports that less than 10% of cocaine entering the US transits through Venezuela. 👉🏽 Read the full report here: https://shorturl.at/GIxnk #DonaldTrump#DrugTrafficking#NicolasMaduro#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #1932 · 09.04.2025 г., 19:59

📰 NEWS | Six Venezuelan Mayors Arrested in Anti-Drug Crackdown Six mayors—five from the ruling PSUV and one from the opposition—have been arrested in Zulia under “Operation Catatumbo Lightning,” targeting drug trafficking and money laundering. Venezuelan Interior Minister Diosdado Cabello said the network operated on the Maracaibo Lake shores and was tied to far-right figures, including María Corina Machado and Colombian ex-presidents Uribe and Duque. Authorities seized 16 tons of high-purity cocaine, submarines, boats, and dismantled paramilitary camps. Further arrests are expected. 🔗 Read our report here: https://venezuelanalysis.com/news/six-venezuelan-mayors-arrested-in-anti-drug-crackdown/ #DrugTrafficking#ZuliaState

Venezuelanalysis

@venanalysis · Post #2145 · 17.10.2025 г., 10:02

📰 NEWS | Trinidadian Civilians Killed in US Airstrike as Trump Expands Bombing Campaign Near Venezuela Two citizens from Trinidad and Tobago were among six people killed in a US airstrike that destroyed a boat off Venezuela’s coast. The Trump administration said it targeted a drug-smuggling vessel but provided no evidence. Families insist the men were fishermen. The airstrike is part of a broader US bombing campaign in the Caribbean that has killed 27 people since September, drawing condemnation from Colombia and concerns over civilian safety. Read the full report here 👉https://shorturl.at/JsjMM #DonaldTrump#DrugTrafficking#TrinidadandTobago

Venezuelanalysis

@venanalysis · Post #2114 · 26.09.2025 г., 21:35

🎥 VIDEO | War on Drugs Meets War on Terror: Washington’s New Playbook for Latin America Emma Vigeland from Majority Report sits down with Venezuelanalysis’ José Luis Granados Ceja to break down Washington’s latest aggression in Latin America. From the illegal attacks on Venezuelan boats to threats against Mexico, they explore how U.S. policy is once again fueling instability in the region. 👉 Watch the full video here: https://shorturl.at/xbNqS #DrugTrafficking#USVenezuelaRelations#Mexico

12
ПретходнаСтраница 1 од 2Следна