fork download
  1. import re
  2. file="""*some random text*
  3. ...
  4. ...
  5. ...
  6. tag/delimiter 1
  7. text 1 #extract
  8. text 2 #extract
  9. ... #extract
  10. ... #extract
  11. text n #extract
  12. tag/ending_delimiter
  13. *some random text*
  14. ...
  15. ...
  16. ...
  17. tag/delimiter 2
  18. text 1 #extract
  19. text 2 #extract
  20. ... #extract
  21. ... #extract
  22. text n #extract
  23. tag/ending_delimiter
  24. *some random text*
  25. ...
  26. ...
  27. ...
  28. tag/delimiter n
  29. text 1 #extract
  30. text 2 #extract
  31. ... #extract
  32. ... #extract
  33. text n #extract
  34. tag/ending_delimiter
  35. *some random text until the file ends*"""
  36. data_file = file.splitlines()
  37. block = []
  38. found = False
  39. list_of_starting_delimiters = ['tag/delimiter']
  40. attribute_end = 'tag/ending_delimiter'
  41. curr = []
  42.  
  43. for elem in list_of_starting_delimiters:
  44. for line in data_file:
  45. if found:
  46. curr.append(line)
  47. if line.strip().startswith(attribute_end):
  48. found = False
  49. block.append("\n".join(curr))
  50. curr = []
  51. else:
  52. if line.strip().startswith(elem):
  53. found = True
  54. curr.append(line.strip()) #block = elem
  55.  
  56. if len(curr) > 0:
  57. block.append(curr)
  58.  
  59. for b in block:
  60. print(b)
  61. print("---Next block---")
  62.  
  63.  
Success #stdin #stdout 0s 23296KB
stdin
Standard input is empty
stdout
tag/delimiter 1
text 1   #extract
text 2   #extract
...      #extract
...      #extract
text n   #extract
tag/ending_delimiter
---Next block---
tag/delimiter 2
text 1   #extract
text 2   #extract
...      #extract
...      #extract
text n   #extract
tag/ending_delimiter
---Next block---
tag/delimiter n
text 1   #extract
text 2   #extract
...      #extract
...      #extract
text n   #extract
tag/ending_delimiter
---Next block---