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._py3k import input as _input 
11   
12  import shlex 
13   
14   
15 -class MMCIF2Dict(dict):
16
17 - def __init__(self, filename):
18 with open(filename) as handle: 19 loop_flag = False 20 key = None 21 tokens = self._tokenize(handle) 22 token = next(tokens) 23 self[token[0:5]]=token[5:] 24 for token in tokens: 25 if token=="loop_": 26 loop_flag = True 27 keys = [] 28 i = 0 29 n = 0 30 continue 31 elif loop_flag: 32 if token.startswith("_"): 33 if i > 0: 34 loop_flag = False 35 else: 36 self[token] = [] 37 keys.append(token) 38 n += 1 39 continue 40 else: 41 self[keys[i%n]].append(token) 42 i+=1 43 continue 44 if key is None: 45 key = token 46 else: 47 self[key] = token 48 key = None
49
50 - def _tokenize(self, handle):
51 for line in handle: 52 if line.startswith("#"): 53 continue 54 elif line.startswith(";"): 55 token = line[1:].strip() 56 for line in handle: 57 line = line.strip() 58 if line==';': 59 break 60 token += line 61 yield token 62 else: 63 tokens = shlex.split(line) 64 for token in tokens: 65 yield token
66 67 68 if __name__=="__main__": 69 70 import sys 71 72 if len(sys.argv)!=2: 73 print("Usage: python MMCIF2Dict filename.") 74 75 filename=sys.argv[1] 76 77 mmcif_dict = MMCIF2Dict(filename) 78 79 entry = "" 80 print("Now type a key ('q' to end, 'k' for a list of all keys):") 81 while(entry != "q"): 82 entry = _input("MMCIF dictionary key ==> ") 83 if entry == "q": 84 sys.exit() 85 if entry == "k": 86 for key in mmcif_dict: 87 print(key) 88 continue 89 try: 90 value=mmcif_dict[entry] 91 if isinstance(value, list): 92 for item in value: 93 print(item) 94 else: 95 print(value) 96 except KeyError: 97 print("No such key found.") 98