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

Резултати

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

Пребарај: #statistical

当前筛选 #statistical清除筛选
Data Analytics

@sqlspecialist · Post #1644 · 23.05.2025 г., 18:46

✨The STAR method is a powerful technique used to answer behavioral interview questions effectively. It helps structure responses by focusing on Situation, Task, Action, and Result. For analytics professionals, using the STAR method ensures that you demonstrate your problem-solving abilities, technical skills, and business acumen in a clear and concise way. Here’s how the STAR method works, tailored for an analytics interview: 📍 1. Situation Describe the context or challenge you faced. For analysts, this might be related to data challenges, business processes, or system inefficiencies. Be specific about the setting, whether it was a project, a recurring task, or a special initiative. Example: “At my previous role as a data analyst at XYZ Company, we were experiencing a high churn rate among our subscription customers. This was a critical issue because it directly impacted revenue.”* 📍 2. Task Explain the responsibilities you had or the goals you needed to achieve in that situation. In analytics, this usually revolves around diagnosing the problem, designing experiments, or conducting data analysis. Example: “I was tasked with identifying the factors contributing to customer churn and providing actionable insights to the marketing team to help them improve retention.”* 📍 3. Action Detail the specific actions you took to address the problem. Be sure to mention any tools, software, or methodologies you used (e.g., SQL, Python, data #visualization tools, #statistical#models). This is your opportunity to showcase your technical expertise and approach to problem-solving. Example: “I collected and analyzed customer data using #SQL to extract key trends. I then used #Python for data cleaning and statistical analysis, focusing on engagement metrics, product usage patterns, and customer feedback. I also collaborated with the marketing and product teams to understand business priorities.”* 📍 4. Result Highlight the outcome of your actions, especially any measurable impact. Quantify your results if possible, as this demonstrates your effectiveness as an analyst. Show how your analysis directly influenced business decisions or outcomes. Example: “As a result of my analysis, we discovered that customers were disengaging due to a lack of certain product features. My insights led to a targeted marketing campaign and product improvements, reducing churn by 15% over the next quarter.”* Example STAR Answer for an Analytics Interview Question: Question: *"Tell me about a time you used data to solve a business problem."* Answer (STAR format): 🔻*S*: “At my previous company, our sales team was struggling with inconsistent performance, and management wasn’t sure which factors were driving the variance.” 🔻*T*: “I was assigned the task of conducting a detailed analysis to identify key drivers of sales performance and propose data-driven recommendations.” 🔻*A*: “I began by collecting sales data over the past year and segmented it by region, product line, and sales representative. I then used Python for #statistical#analysis and developed a regression model to determine the key factors influencing sales outcomes. I also visualized the data using #Tableau to present the findings to non-technical stakeholders.” 🔻*R*: “The analysis revealed that product mix and regional seasonality were significant contributors to the variability. Based on my findings, the company adjusted their sales strategy, leading to a 20% increase in sales efficiency in the next quarter.” Hope this helps you 😊