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

Резултати

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

Пребарај: #smartphones

当前筛选 #smartphones清除筛选
🦅 [ perspective ix ]

@perspectiveix · Post #1038 · 10.12.2017 г., 20:30

While time spent on all game consoles remained flat, usage of apps & the web on #smartphones saw notable lifts in time spent. Overall, media usage increased by 30 mins in Q2 2017. 🚀@PerspectiveIX

Hashtags

🦅 [ perspective ix ]

@perspectiveix · Post #1261 · 11.05.2018 г., 19:00

​​📱Have We Reached Peak Smartphone? After a decade of growth, the global #smartphone market came to a standstill in 2017. According to latest estimates from market research firm IDC, a worldwide total of 1,472 million #smartphones were shipped in 2017, virtually unchanged from the 1,473 million units shipped in the previous year. 🚀@PerspectiveIX 🌳https://prs.pctvix.co/2rBpZT1

🦅 [ perspective ix ]

@perspectiveix · Post #1806 · 02.05.2019 г., 09:01

📱Top Grossing Google Play Categories in Q1 2019 There are some stark contrasts here with the top iOS grossing categories in Q1 2019. We're all just humans with #smartphones, and yet, how #iOS users and #Android users spend their money on mobile varies so drastically. Business apps are getting a lot more spend from Android users. Entertainment is still a power category, but definitely less so in North America and Latin America. The most significant drop-off is spending on Social apps. The category is completely gone from the top 10 Google Play picture. Like Social, the Lifestyle category is gone from the top list altogether. 🚀@PerspectiveIX via Apptopia.

🦅 [ perspective ix ]

@perspectiveix · Post #1347 · 21.06.2018 г., 19:30

​​📱 vs 📺Mobile Soon to Pass TV in Time Spent But IoT could one day soon capture some of those mobile minutes Americans are spending less time with most major media, with one major exception: #smartphones. In 2018, adults will still dedicate more time per day to #TV—nearly 3 hours, 50 minutes—than to any other medium, but TV time is shrinking, down from 4 hours, 37 minutes in 2012. #Mobile time will increase to 3 hours, 35 minutes in 2018, and by 2019 mobile will be the new leader in time spent, with 3 hours, 43 minutes of engagement vs. TV’s 3 hours, 42 minutes. 🚀@PerspectiveIX ☕️prs.pctvix.co/2M8AAOb

🦅 [ perspective ix ]

@perspectiveix · Post #1192 · 09.04.2018 г., 19:30

​​🎧Smartphones Drive Podcast Usage More than 23 million adults in the U.S. have listened to a #Podcast in the past month on a #Smartphone. That’s double the amount who listened on a computer in 2017. Three years ago, the computer is where the largest podcast audience could be found. From 2014 to 2017, the podcasting audience on smartphones increased by 157%. The growth of podcasting is being driven by #smartphones. 🚀@PerspectiveIX 🌀 ⁣http://prs.pctvix.co/TelegramIX

Online Education

@OnlineEducation10 · Post #70 · 23.02.2021 г., 07:21

As of November 2019: 54 percent of the urban population of 12+ years and 32 percent of the same in the rural areas had internet access 77 percent of urban and 61 percent of rural internet users aged 12 and above used it every day, while 7 percent of urban and 13 percent of rural users used it less than once a week 99 percent of both urban and rural internet users aged 12 yrs. and above used mobile phones to access the internet 433 million people aged 12 yrs. and above, and 71 million people aged 5-11 yrs. were active internet users in India Mobile penetration in India 502.2 million people in India had smartphones as of December 2019 The number of smartphone users is expected to be 859 million and 504 million respectively by 2022 #Online#Education#Trends#Mobile#Internet#Smartphones 👍 Join @OnlineEducation10

🦅 [ perspective ix ]

@perspectiveix · Post #1561 · 24.09.2018 г., 08:00

​​📷How the Camera Industry was Hit by Smartphones Over the past few years, #smartphone cameras have improved significantly. So much so in fact, that many people no longer see the need to carry or buy a dedicated camera. While professionals and photo enthusiasts will always get better results using high-end cameras and lenses, modern #smartphones take pictures that are easily sufficient for the demands of the average consumer. To the camera and photo equipment industry, the rise of smartphone photography has had devastating effects. According to CIPA, a Japan-based industry group with members such as #Olympus, #Canon and #Nikon, worldwide camera shipments dropped nearly 80 percent between 2010 and 2017. 🚀@PerspectiveIX via Statista. ❓What do you usually take photos with?

🦅 [ perspective ix ]

@perspectiveix · Post #1680 · 27.11.2018 г., 10:30

​​📱Your Phone's Radiation For most people nowadays, their #smartphone is within arm's reach 24 hours a day. It's in their pocket while they're at work, it's in their hand on the train ride home and it's on their bedside table as they go to sleep. With this level of proximity and usage, many can't quite shake the niggling feeling that they might be risking damage to themselves in the long run. While conclusive longitudinal research on the effects of cell phone radiation is still hard to come by, for those looking to hedge their bets, this infographic shows the phones that emit the most radiation when held to the ear while calling. The German Federal Office for Radiation Protection (Bundesamt für Strahlenschutz) has a comprehensive database of #smartphones - new and old - and the level of radiation they emit. Following the criteria set for this chart (see footnotes), the current smartphone creating the highest level of radiation is the Mi A1 from Chinese vendor Xiaomi. In fact, the top list is dominated by handsets made by Chinese companies, with #Xiaomi, #OnePlus, #Huawei and #ZTE accounting for 12 of the 15 phones with the largest values. It must be said though, that premium #Apple phones such as the #iPhone 7 and the recently released iPhone 8 are also here to be seen. 🚀@PerspectiveIX via Statista. ❓Would this concern you and the smartphone you might buy?