examples.py (847B)
1 #!/usr/bin/python 2 3 from random import randint 4 5 6 def get_random_example(): 7 File = open("examples.tex", 'r') 8 File.seek(0) 9 10 example_lines = [] 11 record = False 12 13 for i, line in enumerate(File): 14 if i == 0: 15 if not line.startswith("%TOTAL"): 16 raise Exception("No total on first line.") 17 else: 18 total_examples = int( line.split()[1] ) 19 example_number = randint(1, total_examples) 20 continue 21 22 if line.startswith(f"%BEGIN {example_number}"): 23 record = True 24 continue 25 26 if line.startswith(f"%END {example_number}"): 27 record = False 28 break 29 30 if record: 31 example_lines += [line] 32 33 example = ''.join(example_lines) 34 return example 35 36 37 print(get_random_example())