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

Пребарај: #peasants

当前筛选 #peasants清除筛选
Venezuelanalysis

@venanalysis · Post #2011 · 23.06.2025 г., 18:46

📰 NEWS | Campesino Movements Demand Venezuelan Gov’t Step In to Protect Activists from ‘Criminalization’ Attacks Venezuelan campesino movements have denounced the arrest of Lilibeth Rangel in Zulia and the detention of 28 rural producers in Barinas as part of a broader pattern of criminalization. The Small Farmers Movement (MPA) is urging government institutions to intervene and address judicial delays and alleged landowner interference in security operations. Campesino families from La Rubiera and La Fortuna estates have been demanding land titles under the 2001 Land Law for years. 🔗 Read the full report here: https://venezuelanalysis.com/news/campesino-movements-demand-venezuelan-govt-step-in-to-protect-activists-from-criminalization-attacks/ #Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #1754 · 25.09.2024 г., 14:44

On September 21, Venezuelan campesino leader Iraidez Andrade was killed by masked hitmen in Barinas state. He had been a prominent voice in the Las Mercedes land struggle and was working with local communities to secure land for campesino families. Rural organizations have called for justice and an end to impunity for the ongoing violence against campesino leaders. Full report here 👉🏼https://shorturl.at/dzgzG #Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2302 · 11.03.2026 г., 14:38

📹 VIDEO | Rice Producers Protest Agribusiness Pressure in Venezuela Rice producers across Venezuela are taking to the streets ahead of the upcoming harvest, warning that prices offered by agroindustrial firms could leave many farmers unable to cover production costs. Campesino groups say large conglomerates are using their control over silos, imports, and distribution to push prices down, while limited access to credit keeps farmers dependent on company financing. After talks with producers, Agriculture Minister Julio León Heredia announced a provisional price. But campesino organizations warn they were barely represented in negotiations. Click here to read our full report 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/ #Agriculture#Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2285 · 25.02.2026 г., 23:06

📰 NEWS | Venezuela: Rice Producers Denounce Agribusiness Pressure, Demand Gov’t Support for Fair Prices Venezuelan rice producers have staged demonstrations in Barinas, Cojedes, Guárico and Portuguesa, demanding state action to secure fair prices for their crops. According to producer representative Víctor Martínez, agribusiness firms are offering $0.32–0.38 per kilo ahead of harvest, compared to $0.50–0.55 last year. Producers have set a $0.70 per kilo target in negotiations, citing rising input costs and lack of credit access. Growers also report financing agreements in which companies provide inputs and collect up to 60% of the crop as payment. Campesino organizations are considering a rally in Caracas. Government officials have not yet commented. Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/ #Agriculture#Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2075 · 25.08.2025 г., 21:40

📰 NEWS | Venezuela: Turkish Investors to Take Over State-Owned Sugar Mills Under ‘Strategic Alliances’ Venezuela has signed agreements with Turkish investors to manage three state-owned sugar mills — Central Venezuela (Zulia state), Santa Clara (Yaracuy state), and Ezequiel Zamora (Barinas state) — as part of new 'strategic alliances,' Agriculture Minister Julio León announced. Authorities have not disclosed further details. Previous experiences with similar alliances in the countryside have raised concerns among campesinos regarding transparency and impacts on small-scale producers. 🔗 Read the full report here: https://shorturl.at/pwPmt #Peasants#Campesinos#PrivateSector#Sugar

Venezuelanalysis

@venanalysis · Post #1997 · 05.06.2025 г., 19:39

🖊 COLUMN | Venezuela, Popular Power and Coffee Jessica Dos Santos' latest column showcases how 18 communes in Sanare, Venezuela, launched the “Enriquito Colmenárez” coffee-roasting plant after receiving it from the Agriculture Ministry. The grassroots initiative supports campesinos with subsidies, training, and direct diesel access, while preparing to export robusta beans to the US and Russia. The plant will also host a soil lab through a partnership with the United Nations Food and Agriculture Organization (FAO). 🔗 Read the full VA column here: https://shorturl.at/EAU4t #Coffee#Peasants#Campesinos#PopularPower#TalesofResistance