from dataclasses import dataclass
@dataclass
class Record:
times: str = None
name: str = None
room: str = None
array = ["1-ая пара, предмет, аудитория", "2-ая пара, предмет, аудитория",
"2-ая пара, предмет, аудитория", "4-ая пара, предмет, аудитория"]
schedule = [Record(*v.split(',')) for v in array]
new_parsing_times = ["9:40 - 10:30", "10:40 - 12:10", "12:50 - 14:20", "14:30 - 16:00"]
for record, new_times in zip(schedule, new_parsing_times):
record.times = new_times
print(schedule)
import re
input_file = """This is line #aabbcc #ddeeff
This is line #aab66c #ddee44
This is line #aabbcc #cceeff #aa11cc #dd22ff
This is line #aabbcc #ddee00 #dd11ff"""
pattern = re.compile(r'#\w{6}')
def invert(color_to_convert):
table = "".maketrans('0123456789abcdef', 'fedcba9876543210')
return color_to_convert.lower().translate(table).upper()
def replace(s: str):
colors = [invert(color) for color in pattern.findall(s)]
s = pattern.sub("{}", s)
return s.format(*colors)
for line in input_file.split('\n'):
print(replace(line))
This is line #554433 #221100
This is line #554993 #2211BB
This is line #554433 #331100 #55EE33 #22DD00
This is line #554433 #2211FF #22EE00
import asyncio
from time import time
els = list(range(20))
async def rm_list(v):
await asyncio.sleep(5)
print(v)
async def _main():
await asyncio.gather(*(
rm_list(value) for value in els
))
start = time()
loop = asyncio.get_event_loop()
loop.run_until_complete(_main())
loop.close()
print(time() - start)
sells={
... "Маша":"Samsung 20",
... "Максим":"Iphone 6S",
... "Наташа":"Lenovo Legion"
... }
prices={
... "Samsung 20": 300,
... "Iphone 6S": 260,
... "Lenovo Legion": 450
... }
result = [name for name, tel in sells.items() if prices.get(tel, 999) < 350]
>>> print(result)
['Маша', 'Максим']
import re
s = "выставляет на аукцион (214422): 1*Кожаная туника - 900 золота , " \
"нужно вычленить именно число в скобках, у каждого такого сообщения они каждый раз разные."
lot_re = re.compile(r'\((?P<lot_id>\d+)\)')
result = lot_re.search(s).groupdict()
print(result)
{'lot_id': '214422'}
student_tuples = [
... ('john', 'A', 15),
... ('jane', 'B', 12),
... ('dave', 'B', 10),
... ('dave1', 'B', 11),
... ('dave2', 'B', 1),
... ]
... student_tuples.sort(key=lambda student: (student[1], student[2]))
student_tuples
[('john', 'A', 15), ('dave2', 'B', 1), ('dave', 'B', 10), ('dave1', 'B', 11), ('jane', 'B', 12)]
import asyncio
from aiohttp import ClientSession, ClientError
async def check_url(url):
async with ClientSession() as s:
try:
r = await s.head(url)
if r.status != 200:
return url
except ClientError:
return f'error {url}'
URLS = [
'https://ya.ru',
'https://qna.habr.com/',
'https://qna.habr1.com/',
] * 10
async def _main():
fails = await asyncio.gather(*(check_url(url) for url in URLS))
print(fails)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(_main())
loop.close()
from urllib.parse import unquote
unquote('https://www.сайт.ru/moscow?q=%D0%BA%D0%BD%D0%B8%D0%B3%D0%B0+%D0%B4%D0%BB%D1%8F+%D1%87%D1%82%D0%B5%D0%BD%D0%B8%D1%8F')
'https://www.сайт.ru/moscow?q=книга+для+чтения'
или
from urllib.parse import urlparse, parse_qs
v = parse_qs(urlparse('https://www.сайт.ru/moscow?q=%D0%BA%D0%BD%D0%B8%D0%B3%D0%B0+%D0%B4%D0%BB%D1%8F+%D1%87%D1%82%D0%B5%D0%BD%D0%B8%D1%8F').query)
v['q']
['книга для чтения']
t = {
'type': 'message_new',
'object': {
'message': {
'date': 1587065982,
'from_id': 396298943,
'id': 845, 'out': 0,
'peer_id': 396298943,
'text': '',
'conversation_message_id': 329,
'fwd_messages':
[{'date': 1587065973, 'from_id': 396298943, 'text': '',
'attachments': [], 'fwd_messages':
[{'date': 1587065635, 'from_id': 574078662,
'text': 'Мда..Вк на приложении сдохло', 'attachments': [],
'conversation_message_id': 1887}],
'conversation_message_id': 328, 'peer_id': 396298943, 'id': 844}],
'important': False, 'random_id': 0, 'attachments': [], 'is_hidden': False},
'client_info': {
'button_actions': ['text', 'vkpay', 'open_app', 'location', 'open_link'],
'keyboard': True, 'inline_keyboard': True, 'lang_id': 0}},
'group_id': 194081345, 'event_id': '919d7461a9d3217cb9f1b9eb50c7b5299571140d'}
# Можно просто
print(t['object']['message']['fwd_messages'])
# Можно не ловя ошибок
print(t.get('object', {}).get('message', {}).get('fwd_messages'))
# Можно обернуть в функцию и скармливать строку
def get_key(obj: dict, path):
for k in path.split('.'):
obj = obj.get(k, {})
return obj
print(get_key(t, 'object.message.fwd_messages'))
import re
convert_str_re = ''.maketrans({'0': r'\d', '#': r'\S'})
data = ['000', '###', '##.#', '00.0']
re_data = [v.translate(convert_str_re) for v in data]
s = '123'
print([re.findall(v, s) for v in re_data])