Package Bio :: Package PDB :: Module MMCIF2Dict
[hide private]
[frames] | no frames]

Source Code for Module Bio.PDB.MMCIF2Dict

  1  # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk) 
  2  # This code is part of the Biopython distribution and governed by its 
  3  # license.  Please see the LICENSE file that should have been included 
  4  # as part of this package. 
  5   
  6  """Turn an mmCIF file into a dictionary.""" 
  7   
  8  from __future__ import print_function 
  9   
 10  from Bio.File import as_handle 
 11  from Bio._py3k import input as _input 
 12   
 13  import shlex 
 14   
 15   
16 -class MMCIF2Dict(dict):
17 """Parse a mmCIF file and return a dictionary.""" 18
19 - def __init__(self, filename):
20 """Parse a mmCIF file and return a dictionary. 21 22 Arguments: 23 - file - name of the PDB file OR an open filehandle 24 """ 25 with as_handle(filename) as handle: 26 loop_flag = False 27 key = None 28 tokens = self._tokenize(handle) 29 token = next(tokens) 30 self[token[0:5]] = token[5:] 31 i = 0 32 n = 0 33 for token in tokens: 34 if token == "loop_": 35 loop_flag = True 36 keys = [] 37 i = 0 38 n = 0 39 continue 40 elif loop_flag: 41 if token.startswith("_"): 42 if i > 0: 43 loop_flag = False 44 else: 45 self[token] = [] 46 keys.append(token) 47 n += 1 48 continue 49 else: 50 self[keys[i % n]].append(token) 51 i += 1 52 continue 53 if key is None: 54 key = token 55 else: 56 self[key] = token 57 key = None
58 59 # Private methods 60
61 - def _tokenize(self, handle):
62 for line in handle: 63 if line.startswith("#"): 64 continue 65 elif line.startswith(";"): 66 token = line[1:].strip() 67 for line in handle: 68 line = line.strip() 69 if line == ';': 70 break 71 token += line 72 yield token 73 else: 74 tokens = shlex.split(line) 75 for token in tokens: 76 yield token
77 78 79 if __name__ == "__main__": 80 81 import sys 82 83 if len(sys.argv) != 2: 84 print("Usage: python MMCIF2Dict filename.") 85 86 filename = sys.argv[1] 87 88 mmcif_dict = MMCIF2Dict(filename) 89 90 entry = "" 91 print("Now type a key ('q' to end, 'k' for a list of all keys):") 92 while(entry != "q"): 93 entry = _input("MMCIF dictionary key ==> ") 94 if entry == "q": 95 sys.exit() 96 if entry == "k": 97 for key in mmcif_dict: 98 print(key) 99 continue 100 try: 101 value = mmcif_dict[entry] 102 if isinstance(value, list): 103 for item in value: 104 print(item) 105 else: 106 print(value) 107 except KeyError: 108 print("No such key found.") 109