fork download
  1.  
  2. import re
  3. import random
  4.  
  5. regex = r"(?m)^[^\/#]*?([.+-]*\d+(?:\.\d+)?(?:e[+-]?\d+)?) +([^\n]*)"
  6.  
  7. test_str = """
  8.  
  9. 0.3 играть
  10. 0.3 кодить
  11. 0.2 спать
  12. 0.01 сделать уборку
  13. 0.5 разминка шеи
  14.  
  15. -0.7 временно отключённый пункт
  16. Комментарии свободно где угодно можно писать
  17. Даже тут 0.4 гулять
  18.  
  19.  
  20.  
  21. """
  22.  
  23. matches = re.finditer(regex, test_str)
  24. r=[]
  25. s=[]
  26.  
  27.  
  28.  
  29. for matchNum, match in enumerate(matches, start=1):
  30. class MyException(Exception):
  31. ...
  32. N=len(match.groups())
  33. if (N==2):
  34. try:
  35. ww=float(match.group(1))
  36. if (ww<=0):
  37. raise MyException()
  38. r+=[ww]
  39. s+=[match.group(2)]
  40. print(f'{r[-1]} : {s[-1]}')
  41. except MyException as e:
  42. print(f" - {match.group(2)}")
  43. except Exception as e:
  44. print(f'Err : {e} : {match.group()}')
  45.  
  46. N=sum(r)
  47. print('\n')
  48. def roll():
  49. if (N==0):
  50. print("Пусто")
  51. return
  52. x=random.random()*N
  53. y=x
  54. i=0
  55. while (x>r[i]):
  56. x-=r[i]
  57. i+=1
  58. print(f'{y:.4f}/{N:.4f} : {x:.4f}/{r[i]:.4f} : {s[i]}')
  59.  
  60.  
  61. roll()
  62.  
  63. #print(g)
  64.  
  65. #print(f'{i} :: {match.group(i+1)}')
  66. #for groupNum in range(0, len(match.groups())):
  67. # groupNum = groupNum + 1
  68.  
  69. # print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
  70.  
  71. # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
  72.  
Success #stdin #stdout 0.04s 12136KB
stdin
Standard input is empty
stdout
0.3 : играть
0.3 : кодить
0.2 : спать
0.01 : сделать уборку
0.5 : разминка шеи
    - временно отключённый пункт
0.4 : гулять


0.7454/1.7100 : 0.1454/0.2000 : спать