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

Резултати

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

Пребарај: #business

当前筛选 #business清除筛选
Kursiv Uzbekistan (Eng)

@kursivuzeng · Post #2647 · 23.02.2026 г., 08:02

📈 Uzbekistan Business Confidence Surges in January 2026 💼 Uzbekistan’s business confidence jumped in January 2026, with the composite business climate index reaching 64 points, up 23% year-on-year, according to the Centre for Economic Research and Reforms (CERR). 🌾 Agriculture led growth, rising to 77 points from 48, as nearly half of agribusinesses reported increasing demand. The services sector climbed to 65 points and construction reached 61 points, while industry remained positive at 54 points. 👷‍♂️ Around 22% of companies have already increased staff, 65% plan workforce expansion, and 71% expect higher demand in the coming quarter. ⚖️ More than half of entrepreneurs (57%) reported no major barriers, with taxes, utilities, and access to finance being the most cited challenges. #Business

Hashtags

iDubTG

@idubtg · Post #601 · 26.03.2024 г., 13:00

🪙Custom Intros An upcoming update to the Telegram for Business feature set will include the ability to customize an intro for yourself. Based on a video from the messenger team, business accounts will be able to edit the look of the greeting message screen that is shown in an empty chat with a user. Currently, by default, this space shows a prompt to send a greeting sticker to the other user. #business

Hashtags

TGBlogLeaks

@TGBlogLeaks · Post #538 · 26.03.2024 г., 13:18

🪙Custom Intros An upcoming update to the Telegram for Business feature set will include the ability to customize an intro for yourself. Based on a video from the messenger team, business accounts will be able to edit the look of the greeting message screen that is shown in an empty chat with a user. Currently, by default, this space shows a prompt to send a greeting sticker to the other user. #business

Hashtags

Am Neumarkt 😱

@amneumarkt · Post #526 · 24.01.2024 г., 07:12

#business It's a short essay from HBR. The essay is not bad, it's just, somehow, trivial. I didn't know you could write for HBR on such trivial topics. Amazing... https://hbr.org/2024/01/getting-machine-learning-projects-from-idea-to-execution

Hashtags

Am Neumarkt 😱

@amneumarkt · Post #150 · 14.01.2021 г., 09:29

#business In 2015, there was a company called SixFold. They were one of the first heroes to disrupt an industry that has not changed much for a century, the freight market. They investigated the situation, established their hypothesis, created MVP. They did not succeed. The image is a summary of their post mortem. There are at least two learning from this story. - Think in terms of the utility function. Do not just point out blocks of reasons. Write down the utility function for the situation and make assumptions on the parameters. - Swarm intelligence sometimes works better than one might expect. Improvements in swarm intelligence take a lot of effort if one does not have a smart plan. Here is the article by their CEO: https://medium.com/@MartKelder/end-of-road-for-trucking-startup-palleter-523a4a906fe9

Hashtags

Journey to Fluency

@fluencyinenglish · Post #6217 · 02.07.2018 г., 09:08

#vocabulary #business @fluencyinenglish ✅چند تا لغت بسیار کاربردی در مورد اقتصاد🇺🇸🇬🇧 @fluencyinenglish ✴️Funds : available money پول در دسترس, سرمایه .@fluencyinenglish ✴️Commodity : something that can be bought and sold متاع, کالا, جنس .@fluencyinenglish ✴️Retail price : how much something costs to buy in a shop قیمت خرده فروشی .@fluencyinenglish ✴️Market price : how much something costs to buy in large quantities قیمت عمده فروشی . ✴️Income - money that someone gets from working درآمد, عایدی .@fluencyinenglish ✴️Middleman - a person or company that buys from producers and sells to cus at a profit. واسطه, شرکت واسط, که در ایران پول توی همین کاره😊 @fluencyinenglish ✴️Loan shark- someone who lends money to people at a very high rate of interest رباخوار, صد رحمت به کوسه, افراد یا بانکهایی که خودتون میشناسید . ✴️Trader/ dealer- someone who buys and sells things خریدار فروشنده @fluencyinenglish ✴️Consumer : someone who buys something or uses services مصرف کننده, فرد بینوایی که همه ی سود از او استخراح میشه😢 @fluencyinenglish ✴️Player- a person or organization that influences a situation, especially in business or politics. مهره ی موثر در وضعیت اقتصادی یا سیاسی, همون ژن خوبها @fluencyinenglish

The Telegram Times

@TheTGTimes · Post #313 · 03.04.2024 г., 22:41

📰Chat Bots With Telegram Business, you can connect Telegram bots that will process and answer messages on their behalf. This allows businesses to seamlessly integrate any existing tools and workflows, or add AI assistants that manage their chats. When adding a chatbot, you can configure which chats the bot can access, such as excluding all chats with your contacts, or only responding to new chats. 🏪What's Telegram Business? #Business | #Premium 👉The TG Times

The Telegram Times

@TheTGTimes · Post #312 · 03.04.2024 г., 22:41

📰Links to Chat To make it even easier for customers to reach out, you can create links to chat with your business, for example a button to reserve a table or track an order. When tapped, these links instantly open a chat with you and paste a suggested message for the user. You can use these links both inside and outside of Telegram. 🏪What's Telegram Business? #Business | #Premium 👉The TG Times

The Telegram Times

@TheTGTimes · Post #311 · 03.04.2024 г., 22:41

📰Start Page In the latest version of Telegram (v10.10), you can set a start and welcome message along with a custom sticker on your chat entry screen. 🏪What's Telegram Business? #Business | #Premium 👉The TG Times

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••5960
ПретходнаСтраница 1 од 60Следна