array[:, :, 0]
либо так array[..., 0]
.sections = []
current_section = None
paragraphs = []
for tag in tags: # перебираем теги, которые надо обработать
if tag.name == 'h2':
if current_section is not None:
sections.append( (current_section, paragraphs) )
current_section = tag
paragraphs = []
elif tag.name == 'p':
paragraphs.append(tag)
if current_section is not None:
sections.append( (current_section, paragraphs) )
import asyncio
import aiohttp
import discord
from discord.ext import commands
client = commands.Bot(intents = discord.Intents.default())
async def fetch():
return ... # тут вытаскиваем данные с сайта через aiohttp и возвращаем в удобном нам виде
async def display(results):
global client
pass # тут выводишь результаты в дискорд, используя объект client
async def cycle():
while True:
res = await fetch() # обработку ошибок допиши сам
await display(res)
await asyncio.sleep(300) # задержка в секундах
cycle_task = None
@client.ready
async def on_ready():
global cycle_task
if cycle_task is None: # событие ready может отрабатывать несколько раз, нам нужен только один.
cycle_task = asyncio.get_event_loop().create_task(cycle())
pass # тут делаешь что тебе еще нужно по запуску бота
# когда надо будет остановить цикл, вызови cycle_task.cancel()
bot.run(TOKEN) # запускаешь бота
def tokenize(line: str):
token = []
for ch in line:
if ch.isalnum() or ch == '_':
token.append(ch)
else:
if token:
yield ''.join(token)
token.clear()
yield ch
if token:
yield ''.join(token)
data = 'struct<Milk:array<struct<id:string,type:string>>,Oil:string,batter:array<struct<id:string,type:string>>>'
tokens = list(tokenize(data))
print(tokens)
import typing as t
import enum
class Parser:
@staticmethod
def tokenize(line: str) -> t.Iterable[str]:
token = []
for ch in line:
if ch.isalnum() or ch == '_':
token.append(ch)
else:
if token:
yield ''.join(token)
token.clear()
yield ch
if token:
yield ''.join(token)
def process(self, line: str):
tokens = list(self.tokenize(line))
result = self.do_type(tokens)
if tokens:
raise ValueError('Extra tokens at the end of the line: {0!r}'.format(''.join(tokens)))
return result
def _consume(self, tokens: t.List[str], expected: t.Optional[str] = None):
token = tokens.pop(0)
if expected is not None and token != expected:
raise ValueError(f'Expected {expected!r}, got {token!r}')
return token
def do_type(self, tokens: t.List[str]) -> t.Union[str, t.Dict]:
if tokens[0] == 'struct':
return self.do_struct(tokens)
elif tokens[0] == 'array':
return self.do_array(tokens)
else:
return self._consume(tokens)
def do_struct(self, tokens: t.List[str]) -> t.Dict:
self._consume(tokens, 'struct')
self._consume(tokens, '<')
result = {}
while True:
name, value = self.do_struct_part(tokens)
result[name] = value
if tokens[0] == ',':
self._consume(tokens, ',')
else:
break
self._consume(tokens, '>')
return result
def do_struct_part(self, tokens: t.List[str]) -> t.Tuple[str, t.Union[str, t.Dict]]:
name = self._consume(tokens)
self._consume(tokens, ':')
value = self.do_type(tokens)
return name, value
def do_array(self, tokens: t.List[str]) -> t.Dict:
self._consume(tokens, 'array')
self._consume(tokens, '<')
result = { None: self.do_type(tokens) }
self._consume(tokens, '>')
return result
data = 'struct<Milk:array<struct<id:string,type:string>>,Oil:string,batter:array<struct<id:string,type:string>>>'
p = Parser()
print(p.process(data))