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

Резултати

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

Пребарај: #vainterview

当前筛选 #vainterview清除筛选
Venezuelanalysis

@venanalysis · Post #1813 · 22.11.2024 г., 21:43

Cooperation Jackson is a coop-based organization working for Black self-determination and economic democracy in Jackson, Mississippi. Activist and writer Kali Akuno is one of the project’s founders. In the latest VA interview, Akuno discusses his long-standing relationship with the Bolivarian Revolution and his efforts to build connections between the revolutionary process in Venezuela and the work that is being done in Mississippi. Read the full interview here 👉🏼https://shorturl.at/nwm4z #internationalsolidarity#sanctions#VAInterview

Venezuelanalysis

@venanalysis · Post #1860 · 24.01.2025 г., 19:04

Along the Orinoco River, fishing has long been a way of life rooted in collective work and respect for nature. Under the US blockade, fisher folk in the Ayacucho Commune are addressing challenges with ingenuity and solidarity. From boat rotations to crafting curiaras together, they are building resilience and self-governance while working toward food sovereignty. As José Flores, the state coordinator of fisher folk for the Ayacucho Commune, says, "the river brings us together." 🔗 Read the full report here 👉🏽https://shorturl.at/4OGYk #VAInterview#CommunalandWorkingClassResistance#Communes

Venezuelanalysis

@venanalysis · Post #1855 · 17.01.2025 г., 17:46

In Puerto Ayacucho, Ayacucho Commune fisherfolk combines tradition with communal organization to counter the effects of US sanctions. To secure food sovereignty, they plan to build a refrigeration facility to bypass exploitative intermediaries. As José Flores, state coordinator of fisher people for the Ayacucho Commune, said: 'Fishing is more than work; it binds the community together.' Learn more in VA’s latest Communal Resistance series interview: https://venezuelanalysis.com/interviews/the-ayacucho-commune-a-fishing-community-on-the-orinoco-part-i/ #VAInterview#CommunalandWorkingClassResistance#Communes

Venezuelanalysis

@venanalysis · Post #1737 · 06.09.2024 г., 23:10

Located near Miraflores Palace in Caracas, La Minka Collective operates from a dynamic multi-use cultural space. The building, a former printing press, is adorned with a mural representing Venezuela’s popular history and now hosts classrooms, a radio studio, and a community kitchen, each dedicated to advancing grassroots democracy. In the latest VA interview, Natalia Molina, a founder of the organization, reflects on La Minka’s origins, its cultural projects, and the collective’s work in building a socialist commune while defending the Bolivarian Process after the post-July 28th fascist attacks. Read the full interview here: https://shorturl.at/qoEqK #Communes#Culture#VAInterview

Venezuelanalysis

@venanalysis · Post #1766 · 04.10.2024 г., 17:20

In the latest VA interview, Javier Couso, a keynote speaker at the recent World Congress Against Fascism in Caracas discussed the fascist attacks on Venezuela. He highlighted Venezuela’s resistance to fascist tactics by liberal democracies, marking it as a key player in the global struggle for sovereignty and democracy. 'Venezuela is a beacon in the fight for sovereignty and true democracy,' stated Couso. Read the full interview here 👉🏼https://shorturl.at/Ej6UL #VAInterview#Fascism#PresidentialElections2024

Venezuelanalysis

@venanalysis · Post #1940 · 18.04.2025 г., 19:48

📝 INTERVIEW | Venezuela’s 2025 Elections, Electoral Safeguards and Constitutional Reform: A Conversation with Oliver Rivas In the latest VA interview, Deputy Oliver Rivas breaks down the 2025 candidate selection process, rooted in grassroots assemblies and internal evaluations, and explains how the Simón Bolívar Law protects Venezuela’s democracy from foreign interference. He also looks ahead to the upcoming constitutional reform, which aims to enshrine the commune in the nation’s charter. 🗣 “The process opens a national debate on the type of state we want.” 📖 Read the full interview here: https://venezuelanalysis.com/interviews/venezuelas-2025-elections-electoral-safeguards-and-constitutional-reform-a-conversation-with-oliver-rivas/ #2025ConstitutionalReform#LegislativeRegionalElections2025#VAinterview

Venezuelanalysis

@venanalysis · Post #1786 · 25.10.2024 г., 19:00

Amazonian Huo̧ttö̧ja̧ People and the Bolivarian Process The Río Cataniapo Commune showcases the strength of Indigenous organizations in the Venezuelan Amazon, with approximately 1,500 participants committed to communal living and traditional agriculture. 'Our way of living is far more communitarian than the sabari way of life,' notes Irene Pérez, of the 5 de Julio-Las Pavas Communal Council, is an artisan and campesina, emphasizing their commitment to ensuring no one goes hungry. Read the full interview here: https://venezuelanalysis.com/general/amazonian-huo%cc%a7tto%cc%a7ja%cc%a7-people-and-the-bolivarian-process-rio-cataniapo-commune-part-ii/ #VAInterview#communalresistanceseries#communes#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1838 · 20.12.2024 г., 23:46

Cuban theologian Joel Suárez reflects on Hugo Chávez’s integration of spirituality into his leadership, noting his embodiment of a grassroots liberation theology that combined political vision with cultural expressions like baseball and music. Read the full interview here 👉🏽https://venezuelanalysis.com/interviews/chavez-spirituality-and-celebration-a-conversation-with-joel-suarez-part-ii/ #Chavez#religion#VAInterview

Venezuelanalysis

@venanalysis · Post #1802 · 08.11.2024 г., 21:22

In the Río Cataniapo Commune, communal power and tradition intersect to sustain food sovereignty and resist the impacts of the US blockade. The commune produces its staple casabe from yuca, managing every step from harvest to market. Read the full interview here 👉🏼https://shorturl.at/WRgF9 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1779 · 18.10.2024 г., 21:44

‘The Commune Is Nothing New Here’: The Rio Cataniapo Commune The Rio Cataniapo Commune, located in the Venezuelan Amazon, brings together 1,500 people, mainly Indigenous, to protect the Cataniapo River and develop a sustainable agricultural economy. As Enrique Martínez, a Huo̧ttö̧ja̧ leader, explains: ‘Self-government and collective ownership are part of our heritage.’ Indigenous leadership remains key, but the community also seeks modern improvements while preserving tradition. Read the full interview here 👉🏼https://shorturl.at/Xgst1 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1749 · 20.09.2024 г., 21:13

Ximena González Broquen, a social scientist leading a center at Venezuela’s prestigious Institute for Scientific Research (IVIC) and compiler of several essay collections, discusses the Ethics of Liberation as a framework that challenges the top-down, market-driven logic of conventional scientific research institutes in the latest VA interview. She advocates for a more democratic research environment while aiming to build bridges with organized communities. Read the full interview here 👉🏼https://shorturl.at/PHqTf #VAInterview#Revolution#science#interview

Venezuelanalysis

@venanalysis · Post #1556 · 10.05.2024 г., 21:03

On Fascism and Other Maladies: A Conversation with Luis Britto García One of Venezuela’s most respected intellectuals talks about fascism and corruption scandals in the lead-up to the presidential elections. Read the full interview here 👉🏼shorturl.at/cexUZ #VAInterview#LuisBrittoGarcia#Venezuela#presidentialelections2024#interview#corruption#fascism