Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. from re import compile as compile_pattern
  2.  
  3.  
  4. filename = "morgue.txt"
  5. with open(filename, "r", encoding="utf-8", errors="ignore") as file_handle:
  6.     lines = file_handle.readlines()
  7.  
  8. ## lines now contains a list of all the text lines in the morgue file
  9. print(lines[0]) # prints the first line of the file: "Dungeon Crawl Stone [..]" Can be used to grab version
  10. print(lines[4]) # prints the 5th line (start counting at 0) of the file, can get the score, name, title, level and current hps
  11.  
  12. # go over all lines in the "lines" variable
  13. for line in lines: # store current line in the "line" variable
  14.  
  15.     # Lets find out how much gold, we know that around line 17 the line contains the gold amount, so lets look for it
  16.     if "Gold:" in line: # the text "Gold:" is mentioned in the morgue
  17.         print(line) # Can remove this test/debuggin by adding # at the start
  18.  
  19.         # So lets grab all the digits after "Gold: ". We do not know how many, so let's use regex
  20.         # First we define a pattern:
  21.         #    1. Look for the text 'Gold: '
  22.         #    2. '()' means to capture what is inside into a group, means we want to grab this
  23.         #    3. '\d' means to look for digits (i.e. 0-9) and '+' means at least one, but grab all
  24.         pattern = compile_pattern('Gold: (\d+)')
  25.         # Apply the pattern search on the line we know as "Gold: " in it and store the result in 'match'
  26.         match = pattern.match(line)
  27.         if not match: # in case of bug, catch no match
  28.             print("Error, no gold found on ", line)
  29.             exit(1) # We have a bug, lets just quit and fix it
  30.         # grab the gold amount that we stored the first group
  31.         gold = match.group(1)
  32.         print("This character had ", gold, " gold") # just print the gold since we don't have anything fancy to do with it for now!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement