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

Резултати

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

Пребарај: #ourhawkerculture

当前筛选 #ourhawkerculture清除筛选
NEA Singapore

@NEASingapore · Post #260 · 17.09.2021 г., 04:30

We can’t leave out the signature carrot cake when talking about #OurHawkerCulture, and no, we don’t mean the dessert! Also known as Chai Tow Kway, this savoury dish is made from rice flour and radish.

NEA Singapore

@NEASingapore · Post #296 · 16.12.2021 г., 03:45

Today is the first anniversary of the UNESCO inscription for Singapore’s Hawker Culture, so let’s come together to celebrate, support, and safeguard #OurHawkerCulture! #DidYouKnow many of our hawker dishes originated from the food cultures of different immigrant groups who settled in Singapore? Over time, they have evolved to become the distinctive local dishes that we love, and form an important part of our food heritage. Head down to your favourite hawker stall this week to show your support!

NEA Singapore

@NEASingapore · Post #151 · 16.01.2021 г., 01:00

#DidYouKnow then Prime Minister Lee Kuan Yew laid the foundation stone for Geylang Serai Market back in 1963? It was rebuilt in 2009 with its architecture inspired by the Malay community’s cultural heritage. As part of the efforts to safeguard our #OurHawkerCulture, we want to hear from you about what you hope to see in #OurHawkerCentres of the future. Tell us your views and ideas at https://go.gov.sg/sghf-form by 31 Jan 2021, and stand a chance to win a limited edition #OurHawkerCulture CEPAS card. Terms & conditions apply: https://go.gov.sg/sthctc

NEA Singapore

@NEASingapore · Post #949 · 18.11.2024 г., 01:13

🍜 Ever wonder how the monthly price-based tender system for hawkers work? Every month, NEA offers vacant food and market stalls through open tenders. This ensures stalls are allocated fairly and transparently. When new hawkers successfully bid for a stall, their rent for the first three years will be based on their bid. At the end of the 3-year tenancy term, the rent is then adjusted over time to match the Assessed Market Rent (AMR), which is determined by an independent valuation. This AMR takes into account various factors such as footfall, stall sizes, and tendered stall rentals at the hawker centres. The median AMR for non-subsidised cooked food stalls has remained constant since 2019 at about $1,200 per month. 📢 While past tenders may be considered in AMR, extremely high tender bids will not be considered in the valuation of the AMR. Curious about becoming a hawker or just want to learn more? Click here: go.gov.sg/info-stallholders #SupportOurHawkers#OurHawkerCulture#OurHawkerCentres

NEA Singapore

@NEASingapore · Post #941 · 16.11.2024 г., 01:00

In 2020, Singapore’s hawker culture was officially inscribed onto the UNESCO Representative List of Intangible Cultural Heritage of Humanity. But let's not stop there! Let’s continue to #SupportOurHawkers and keep #OurHawkerCulture thriving for generations to come. P.S. Don’t forget to use your CDC vouchers before they expire! Check out the participating stalls at #OurHawkerCentres here: gowhere.gov.sg/cdcvouchersmerchants

NEA Singapore

@NEASingapore · Post #937 · 14.11.2024 г., 05:41

🍜 Supporting Our Hawkers: The Government sets policies to support our hawkers and provide them with a conducive operating environment, to ensure that they are able to provide Singaporeans with affordable food at #OurHawkerCentres. You can #SupportOurHawkers too! Visit your favourite stall or try new ones today. P.S. Don’t forget to use your CDC vouchers before they expire on 31 Dec 2024 (Tue)! #OurHawkerCulture

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