def __read_times(): """Read times between keystrokes and save them in a Markov chain.""" chain = MarkovChain() a = getch() sys.stdout.write(a) while a != '\r': start = time.time() b = getch() end = time.time() t = end - start chain.add_value(a, b, t) a = b sys.stdout.write(a) sys.stdout.write('\n') return chain
class MarkovTimeReader: """Class to read times between keystrokes and return a Markov chain. - __chain: MarkovChain used for computations. - __text: List used to store input characters. - __times: List used to store times. """ def __init__(self): """Init.""" self.__chain = MarkovChain() self.__text = list() self.__times = list() def __read_character(self): """Read a character and return it along with a time.""" start = time.time() input_char = getch() end = time.time() t = end - start return input_char, t def __backspace(self): """When the input character is a backspace.""" if self.__text: sys.stdout.write('\b \b') if len(self.__text) > 1: previous = self.__text.pop() ante_previous = self.__text[-1] old_time = self.__times.pop() self.__chain.add_value(ante_previous, previous, - old_time) def __normal_character(self, input_character, interval): """When the input character is a normal character. - input_character: Input character. - interval: Time interval. """ if self.__text: previous = self.__text[-1] self.__chain.add_value(previous, input_character, interval) self.__times.append(interval) def read(self): """Read characters. Note that the object's internals are reset before reading characters. (Meaning it is possible to read countless MarkovChain using the same MarkovTimeReader.) """ # Reset the object. self.__init__() go_on = True while go_on: input_character, interval = self.__read_character() go_on = input_character != '\r' if go_on: if input_character == '\x7f': self.__backspace() else: self.__normal_character(input_character, interval) self.__text.append(input_character) sys.stdout.write(input_character) sys.stdout.write('\n') return self.__chain