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

Резултати

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

Пребарај: #wish

当前筛选 #wish清除筛选
Journey to Fluency

@fluencyinenglish · Post #7001 · 28.03.2019 г., 03:43

‍ #wish @fluencyinenglish ❇️ کاربردهای کلمه “wish” به معنای خواستن، آرزو، میل داشتن 🔷 Wish + to + infinitive همان معادل want to است اما کمتر رایج است و رسمی تر. 👉 I wish to see the manager. 👉 Wish + somebody + something 🔷 wish + somebody + something تقدیم آرزوهای خوب برای دیگران 👉 I wish you all the best in your new job. 🔶 همانند مثال اخیر را میتوان همراه با فعل نیز به کار برد، که در آن صورت بایستی از hope استفاده نماییم. 👉 We wish you the best of luck. 👉We hope you have the best of luck. 🔷 Wish + would / could صحبت درباره ی آرزوها و تمایلات آینده. 👉 I don’t like my work. I wish I could get a better job. 👉 That’s a dreadful noise. I wish it would stop. 🔷 Wish + (that) + past simple صحبت درباره ی شرایطی که نسبت به آن پشیمان هستیم و تمایل داریم در حال یا آینده، متفاوت از گذشته باشند. 👉 I wish that I had a big house (I don't have a big house, but it's a nice idea!). 👉 I wish that we didn't need to work today (we do need to work today, unfortunately). 🔑نکته : در اکثر متون و مکالمات رسمی انگلیسی، مشاهده خواهید کرد که به جای was از were استفاده می شود، لذا هر دو مورد صحیح می باشند. 👉 I wish I were rich 👉 I wish I was rich 🔷 Wish + (that) + past perfect صحبت درباره ی موقعیتی که در گذشته اتفاق افتاده است و ما نسبت به آن پشیمانیم. 👉 I wish that I had studied harder at school. (I didn't study hard at school, and now I'm sorry about it.) 👉I wish that I hadn't eaten so much yesterday! (But I did eat a lot yesterday. Now I think it wasn't a good idea.) @fluencyinenglish

Hashtags

Journey to Fluency

@fluencyinenglish · Post #6410 · 04.09.2018 г., 18:08

#grammar #wish #hope @fluencyinenglish @ieltsstrategies How should I use "I hope" and "I wish"? @fluencyinenglish @ieltsstrategies ✅If you want to use "I hope" and "I wish" correctly, you just need to memorize these two phrases: I hope I can... I wish I could... You may be wondering: why do English speakers use the present tense for "hope" and the past tense for "wish"? The secret is that "could" is not really past tense. It looks like past tense, but it's secretly something different. It's the "unreal" aspect. In other words, it expresses something that's not really true, or not very likely. We use "wish" to talk about things that are impossible, or things that probably won't happen: I wish I could fly. I wish there were more hours in the day. I wish I'd studied something a little more practical. On the other hand, we use "I hope..." when there's a good chance that something might happen. You can use it to say what you want to happen in the future: I hope this cake turns out OK. I hope we can still be friends. The grammar of "wish" and "hope" Here's how "wish" and "hope" look in present, past, and future. @fluencyinenglish @ieltsstrategies ❇️Present I hope this is the last mistake. I wish my phone worked here. @fluencyinenglish @ieltsstrategies ❇️Past I hope Antonio got home safely.* I wish you'd told me sooner. * You can't use "hope" to talk about something in the past, unless you don't know what happened yet. In this example, you haven't heard whther Antonio got home safely. @fluencyinenglish @ieltsstrategies ❇️Future I hope it stops raining soon.* I wish it would stop raining. * You follow "hope" with the present tense of a verb, even when you're talking about the future. So you say "I hope it stops" instead of "I hope it will stop." @fluencyinenglish @ieltsstrategies

JS Organization

@jsorganization · Post #401 · 18.06.2024 г., 08:03

Public Wishing With Show Profile Photo Post. Javascript Code🤖 Command Name : /post Code ; Api.sendPhoto({ chat_id: "@JSOrganization",// Replace To Your Channel Username photo:"https://t.me/JSOrganization" , caption: "*👋Hello! @JSOrganization*", parse_mode: "Markdown", reply_markup: {inline_keyboard : [[{text: "CLICK TO WISH ", callback_data: "/post2"}]] } }) Command Name :/post2 Code: // Get the user Telegram ID let userId = user.telegramid; // Array of random wishing captions const randomCaptions = [ "May your wishes come true! 🌟", "Sending you warm wishes on this special day! 🌸", "Wishing you happiness and prosperity!", "May your heart be filled with joy and peace.", "Here's to a wonderful Eid ul Adha celebration!" ]; // Function to get a random element from an array function getRandomElement(array) { return array[Math.floor(Math.random() * array.length)]; } // Define the new property name const newPropertyName = "hasGreeted"; // Check if the user has already greeted if (!User.getProperty(newPropertyName)) { // Increment the total wishes by 1 let totalWishes = Bot.getProperty("total_wishes", 0) + 1; Bot.setProperty("total_wishes", totalWishes, "integer"); // Set a flag to indicate that the user has greeted User.setProperty(newPropertyName, true, "boolean"); // Send the response with an alert Api.answerCallbackQuery({ callback_query_id: request.id, text: `Successfully Wished 🌟\n\nTotal Wishes: ${totalWishes}`, show_alert: true }); // Select a random wishing caption let randomCaption = getRandomElement(randomCaptions); // Prepare the enhanced caption with the updated total wishes count and random wishing caption let caption = `${user.first_name}, wishing you all a blessed Eid ul Adha! 🌸\n\n` + `Thank you for your wish! ${randomCaption}\n\n` + `Total Wishes So Far: ${totalWishes}`; // Edit the message with the updated caption and media Api.editMessageMedia({ chat_id: request.chat_id, message_id: request.message.message_id, media: { type: "photo", media: "t.me/" + user.username, caption: caption }, parse_mode: "markdown", reply_markup: { inline_keyboard: [ [{ text: "✨ Wish Now ✨", callback_data: "/post2"}] ] } }); } else { // User has already greeted, no action needed Api.answerCallbackQuery({ callback_query_id: request.id, text: "You have already greeted!", show_alert: true }); } Replace Your Greetings Random Message As Your Wish 🔴 #Greeting#Wish#EidPost#PublicWish#BotsBusiness#JSOrganization ©@JSOrganization🤖 If Anyone Face Any Error Or Problem. So Message@itsSowrov🙂

跑跑資訊站 KartInfo

@KartInfoTW · Post #403 · 21.07.2022 г., 09:59

韓服 2022 跑跑聯賽第二季將於本週六開打,本季聯賽一大看點就是首位台灣選手「NEAL」參戰,也讓更多台服玩家開始關注韓服聯賽,相信本次聯賽原廠也將秉持最高原則呈現最精彩的賽事給觀眾,更多聯賽資訊和活動獎勵,立即點擊查看 👇👇 🏁 詳細聯賽資訊:https://kinf.cc/Xiq1U ▶️ 追蹤 Google 新聞:https://kinf.cc/gn ▶️ 立即加入 Discord:https://kinf.cc/dc #跑跑卡丁車#KartRider#韓服#職業#聯賽#跑跑聯賽#카트리그#第二季#Season2#懶人包#NEAL#DFIBLADES#KWANGDONGFreecs#LiivSANDBOX#Sinkhole#Savage#FINALEesports#APEX#WISH#開幕賽