MCPcopy Create free account
hub / github.com/CyberPoint/libpgm / dictload

Method dictload

libpgm/dictionary.py:42–84  ·  view source on GitHub ↗

Load a dictionary from a JSON-like text in a text file located at *path* into the attribute *alldata*. In order for this function to execute successfully, the text file must have the proper formatting, particularly with regard to quotation marks. See :doc:`unittestdict` for

(self, path)

Source from the content-addressed store, hash-verified

40 '''An internal representation of a key-indexable dictionary.'''
41
42 def dictload(self, path):
43 '''
44 Load a dictionary from a JSON-like text in a text file located at *path* into the attribute *alldata*.
45
46 In order for this function to execute successfully, the text file must have the proper formatting, particularly with regard to quotation marks. See :doc:`unittestdict` for an example. Specifically, the function can get rid of excess whitespace, convert ``.x`` to ``0.x`` in decimals, and convert ``None`` to ``null``, but nothing else.
47
48 Arguments:
49
50 1. *path* -- Path to the text file (e.g. "mydictionary.txt")
51
52 Attributes modified:
53
54 1. *alldata* -- The entire loaded dictionary.
55
56 The function also returns an error if nothing was loaded into *alldata*.
57
58 '''
59 f = open(path, 'r')
60 ftext = f.read()
61 assert (ftext and isinstance(ftext, str)), "Input file is empty or could not be read."
62
63
64 # alter for json input, if necessary
65 loaded = False
66 try:
67 self.alldata = json.loads(ftext)
68 loaded = True
69 except ValueError:
70 pass
71
72 if not loaded:
73 try:
74 ftext = ftext.translate(None, '\t\n ')
75 ftext = ftext.replace(':', ': ')
76 ftext = ftext.replace(',', ', ')
77 ftext = ftext.replace('None', 'null')
78 ftext = ftext.replace('.', '0.')
79 self.alldata = json.loads(ftext)
80 except ValueError:
81 raise ValueError, "Convert to JSON from input file failed. Check formatting."
82 f.close()
83
84 assert isinstance(self.alldata, dict), "In method dictload, path did not direct to a proper text file."
85
86
87

Callers 3

loadMethod · 0.80
loadMethod · 0.80
loadMethod · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected