-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.py
122 lines (91 loc) · 2.88 KB
/
util.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#These utilities are from Baker et. al (2015)
import os
import codecs
utf8 = False
def writeToFile(text, filepath):
print "writing: " + filepath
if (utf8):
with codecs.open(filepath, 'w', 'UTF-8') as f:
f.write(text)
f.close()
else:
with open(filepath, 'w') as f:
f.write(text)
f.close()
def convertDicToList(dic): # sorts the keys in order then returns a list of values according to that order
retList = []
sortedKeys = sorted(dic.keys())
# print "size of sorted keyes: " + str(len(sortedKeys))
for key in sortedKeys:
retList.append(dic[key])
# print "size of returnList " + str(len(retList))
return retList
def openFileAsLines(filepath):
return readFileAsString(filepath).splitlines()
def fileExisits(filePath):
return os.path.isfile(filePath)
def readFileAsString(filePath):
if (utf8):
return codecs.open(filePath, "r", 'utf-8').read()
else:
return open(filePath).read()
def removeIfExisits(filePath):
if os.path.isfile(filePath):
os.remove(filePath)
print "removed : " + filePath
else:
print filePath + " doesn't exist"
def incrmentDic(dic, keyToAdd):
value = 1
if (keyToAdd in dic.keys()):
value = dic[keyToAdd] + 1
dic[keyToAdd] = value
def listToString(inputlist, delmiter):
retStr = ""
for item in inputlist:
if (not item): continue
retStr += str(item) + delmiter
return retStr
def dicToStr(dic):
retStr = ""
keys = dic.keys()
for i in range(0, len(keys)):
retStr += str(i) + "\t" + str(dic[keys[i]]) + "\t" + keys[i] + "\n"
return retStr
def removeEmptyItemsFromList(originalList):
newList = []
for item in originalList:
item = item.strip()
if (item == None or item == ""): continue
newList.append(item)
return newList
def stringToDict(dicStr):
retDic = {}
for line in dicStr.splitlines():
splits = line.split("\t")
key = splits[2].strip()
value = splits[1].strip()
retDic[key] = value
return retDic
def stringToList(inputStr, delemiter, delemiterGoesFirst=False):
retList = []
for item in inputStr.split(delemiter):
item = item.strip()
retList.append(item)
if (delemiterGoesFirst):
retList = retList[1:] # remove first item which is always empty string
else:
retList = retList[:-1] # remove last item which is always empty string
return retList
def isEmptyList(alist):
if not isinstance(alist, list): raise ValueError("instance must be a list")
if not alist: return 1
if (len(alist) == 0): return 1
for item in alist:
if item.strip() != "":
return 0
return 1
def createDirIfNotExist(path):
if not os.path.exists(path):
print "creating dir :" + path
os.makedirs(path)