This repository was archived by the owner on Aug 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathutil.py
More file actions
54 lines (42 loc) · 1.25 KB
/
util.py
File metadata and controls
54 lines (42 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
Utility functions
'''
'''
This code is borrowed from the util.py of
nematus project (https://github.com/rsennrich/nematus)
'''
import sys
import json
import cPickle as pkl
import gzip
#json loads strings as unicode; we currently still work with Python 2 strings, and need conversion
def unicode_to_utf8(d):
return dict((key.encode("UTF-8"), value) for (key,value) in d.items())
def fopen(filename, mode='r'):
if filename.endswith('.gz'):
return gzip.open(filename, mode)
return open(filename, mode)
def load_dict(filename):
try:
with open(filename, 'rb') as f:
return unicode_to_utf8(json.load(f))
except:
with open(filename, 'rb') as f:
return pkl.load(f)
def load_inv_dict(dict_path):
orig_dict = load_dict(dict_path)
idict = {}
for words, idx in orig_dict.iteritems():
idict[idx] = words
return idict
def load_config(basename):
try:
with open('%s.json' % basename, 'rb') as f:
return json.load(f)
except:
try:
with open('%s.pkl' % basename, 'rb') as f:
return pkl.load(f)
except:
sys.stderr.write('Error: config file {0}.json is missing\n'.format(basename))
sys.exit(1)