имею например текст "Now we add a timeout, say an hour, or 90 seconds, or whatever. What happens when the first password"
хочу спарсить от ", or" до "seconds," и получить в ответе "90".
НЕ используя регулярок ...
Stack Overflow на русском — это сайт вопросов и ответов для программистов. Присоединяйтесь! Регистрация займёт не больше минуты.
Присоединиться к сообществуимею например текст "Now we add a timeout, say an hour, or 90 seconds, or whatever. What happens when the first password"
хочу спарсить от ", or" до "seconds," и получить в ответе "90".
НЕ используя регулярок ...
НЕ используя регулярок ...
text = "Now we add a timeout, say an hour, or 90 seconds, or whatever. What happens when the first password"
start = text.find(', or') + len(', or')
end = text.find(' seconds')
print(text[start: end])
# 90
PS.
Не знаю почему нельзя регулярки, они ведь упрощают:
import re
m = re.search(r', or (\d+) seconds', text)
print(m.group(1))
# 90
Приведу свое видение parser'а. Но перед тем отмечу, что мой пример излишне сложен под такую простую задачу, и привожу я его только в ознакомительных целях.
# 397d19a3c2cf42559d5e877bd89a0417.py
class TBase:
"""
TBase - базовый класс токена.
Некоторые методы базового класса
должны быть переопределены. А
именно does_it и express. Они
будут именно методами класса
(@classmethod).
"""
'''
Lexer должен иметь доступ ко всем
классам, унаследованным от TBase.
Для этого коллекционируем их в instances.
'''
instances = list()
def __init__(self, value=None):
self.value = value
def __init_subclass__(cls):
TBase.instances.append(cls)
return cls
def __str__(self):
value = '' if self.value == None\
else f"({self.value})"
return f"{self.Type}{value}"
@property
def Type(self):
return self.__class__.__qualname__
@classmethod
def does_it(self, lexer):
"""
Возвращает true, если на текущем этапе
токен может определиться из lexer'а.
"""
raise NotImplementedError(
"Method should be overridden.")
@classmethod
def express(self, lexer):
"""
Возвращает экземпляр токена, значение
которого получено разбором lexer'а.
"""
raise NotImplementedError(
"Method should be overridden.")
class TWhitespaces(TBase):
@classmethod
def does_it(cls, lexer):
return lexer.current_char.isspace()
@classmethod
def express(cls, lexer):
while lexer.current_char != None and\
lexer.current_char.isspace():
lexer.advance()
return cls()
class TWord(TBase):
@classmethod
def does_it(cls, lexer):
return lexer.current_char.isalpha()
@classmethod
def express(cls, lexer):
value = str()
while lexer.current_char != None and\
lexer.current_char.isalpha():
value += lexer.Eat()
return cls(value)
class TSpecialChar(TBase):
CHARS = \
list(".,?!-")
@classmethod
def does_it(cls, lexer):
return lexer.current_char in\
TSpecialChar.CHARS
@classmethod
def express(cls, lexer):
value = str()
while lexer.current_char in TSpecialChar.CHARS:
value += lexer.Eat()
return cls(value)
class TInt(TBase):
@classmethod
def does_it(cls, lexer):
return lexer.current_char.isdigit()
@classmethod
def express(cls, lexer):
value = str()
while lexer.current_char != None and\
lexer.current_char.isdigit():
value += lexer.Eat()
value = int(value)
return cls(value)
class Lexer:
"""
Синтаксически разбирает строковые
данные на объявленные токены в
приоритете их объявления
(расположения в TBase.instances).
"""
def __init__(self, data):
self.data = data
self.tokens = list()
self.current_pos = -1
self.current_char = None
"""
Инициализируем переменные current_*
и разбираем data на токены.
"""
self.advance()
self.express()
def advance(self, adjust: int=1):
"""
Продвигается в self.data на adjust
символов.
Текущий символ считается None при
достижении конца.
"""
self.current_pos += adjust
self.current_char = self.data[self.current_pos]\
if self.current_pos < len(self.data) else None
def Eat(self, *args):
"""
Возвращает текущий символ;
вызывает advance с переданными
аргументами.
"""
retr = self.current_char
self.advance(*args)
return retr
def traceback(self):
"""
Возвращает отрывок с последней
пройденной частью.
"""
begin = max(0, self.current_pos - 12)
end = min(len(self.data),
self.current_pos + 1)
excerpt = self.data[begin:end]
return excerpt + '<'
def express(self):
"""
Выполняет синтаксический разбор
собственных данных на токены.
"""
while self.current_char != None:
success = False
for instance in TBase.instances:
if instance.does_it(self):
token = instance.express(self)
self.tokens.append(token)
success = True
break
if not success:
raise SyntaxError(
"Unknown syntax.\n\t" +\
self.traceback())
def BetweenWords(
data,
begin_word,
end_word,
with_whitespaces=False):
"""
Возвращает токены, которые находятся между
TWord(begin_word) и TWord(end_word).
Если был встречен begin_word, но до
конца отсутствовал end_word, то его
отстуствие будет проигнорировано.
"""
retr = list()
now_in = False
for token in Lexer(data).tokens:
if now_in:
if token.Type == "TWord":
if token.value == end_word:
now_in = False
break
if not with_whitespaces:
if token.Type == "TWhitespaces":
continue
retr.append(token)
else:
if token.Type == "TWord":
if token.value == begin_word:
now_in = True
return retr
if __name__ == "__main__":
text = "Now we add a timeout, say an hour, or 90 seconds, or whatever. What happens when the first password"
# Информация о всех токенах:
# print(', '.join([str(token) for token in Lexer(text).tokens]))
tokens = BetweenWords(
text, "or", "seconds")
for token in tokens:
print(token)
print('-' * 10)
result = str(tokens[0].value)
print(result)