Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

""" 

Module provides functions for reading csv-files. 

""" 

from __future__ import unicode_literals, division, print_function 

 

from lingpy.util import read_text_file 

from lingpy.sequence.sound_classes import asjp2tokens 

 

 

def csv2list( 

filename, 

fileformat='', 

dtype=None, 

comment='#', 

sep='\t', 

strip_lines=True, 

header=False 

): 

""" 

Very simple function to get quick (and somewhat naive) access to CSV-files. 

 

Parameters 

---------- 

filename : str 

Name of the input file. 

fileformat : {None str} 

If not specified the file <filename> will be loaded. Otherwise, the 

fileformat is interpreted as the specific extension of the input file. 

dtype : {list} 

If not specified, all data will be loaded as strings. Otherwise, a 

list specifying the data for each line should be provided. 

comment : string (default="#") 

Comment character in the begin of a line forces this line to be 

ignored. 

sep : string (default = "\t") 

Specify the separator for the CSV-file. 

strip_lines : bool (default=True) 

Specify whether empty "cells" in the input file should be preserved. If 

set to c{False}, each line will be stripped first, and all whitespace 

will be cleaned. Otherwise, each line will be separated using the 

specified separator, and no stripping of whitespace will be carried 

out. 

header : bool (default=False) 

Indicate, whether the data comes along with a header. 

 

Returns 

------- 

l : list 

A list-representation of the CSV file. 

 

""" 

# check for correct fileformat 

if fileformat: 

infile = filename + '.' + fileformat 

else: 

infile = filename 

 

if dtype is None: 

dtype = [] 

 

l = [] 

 

# open the file 

infile = read_text_file(infile, lines=True, normalize="NFC") 

 

# check for header 

idx = 0 if header else -1 

 

for i, line in enumerate(infile): 

if line and (not line.startswith(comment) if comment else True) and idx != i: 

if strip_lines: 

cells = [c.strip() for c in line.strip().split(sep)] 

else: 

cells = [c.strip() for c in line.split(sep)] 

if not dtype: 

l += [cells] 

else: 

l += [[f(c) for f, c in zip(dtype, cells)]] 

 

return l 

 

 

def csv2dict( 

filename, 

fileformat=None, 

dtype=None, 

comment='#', 

sep='\t', 

strip_lines=True, 

header=False 

): 

""" 

Very simple function to get quick access to CSV-files. 

 

Parameters 

---------- 

filename : str 

Name of the input file. 

fileformat : {None str} 

If not specified the file <filename> will be loaded. Otherwise, the 

fileformat is interpreted as the specific extension of the input file. 

dtype : {None list} 

If not specified, all data will be loaded as strings. Otherwise, a 

list specifying the data for each line should be provided. 

comment : string (default="#") 

Comment character in the begin of a line forces this line to be 

ignored. 

sep : string (default = "\t") 

Specify the separator for the CSV-file. 

strip_lines : bool (default=True) 

Specify whether empty "cells" in the input file should be preserved. If 

set to c{False}, each line will be stripped first, and all whitespace 

will be cleaned. Otherwise, each line will be separated using the 

specified separator, and no stripping of whitespace will be carried 

out. 

header : bool (default=False) 

Indicate, whether the data comes along with a header. 

 

Returns 

------- 

d : dict 

A dictionary-representation of the CSV file, with the first row being 

used as key and the rest of the rows as values. 

""" 

 

l = csv2list(filename, fileformat, dtype, comment, sep, strip_lines, header) 

return {line[0]: line[1:] for line in l} 

 

 

def csv2multidict(filename, comment='#', sep='\t'): 

""" 

Function reads a csv-file into a multi-dimensional dictionary structure. 

""" 

tsv = csv2list(filename, comment=comment, sep=sep) 

header = tsv[0] 

return {line[0]: dict(zip(header[1:], line[1:])) for line in tsv[1:]} 

 

 

def read_asjp( 

infile, 

family='Indo-European', 

classification='hh', 

max_synonyms=2, 

min_population=lambda x: x > 0 or abs(x) > 1900, 

merge_vowels=True, 

evaluate=False 

): 

# read in all data 

data = csv2list(infile, strip_lines=False) 

 

# find the data confirming to selection, get the header for the 

# classification first 

header = [h.lower() for h in data[0]] 

 

# check for family type 

if not evaluate: 

evaluate = lambda x, y, z: x[y].startswith(z) 

 

# index the classification index 

if ',' in classification: 

a, b = classification.split(',') 

clsA_idx = header.index(a) 

clsB_idx = header.index(b) 

cls_idx = (clsA_idx, clsB_idx) 

else: 

cls_idx = header.index(classification) 

 

# create dictionary to store the data 

D, idx = {}, 1 

 

# lats / longs 

meta = dict( 

coords={}, 

iso={}, 

population={}, 

classification=dict( 

hammarstroem={}, 

ethnologue={}, 

wals={}, 

wals_genus={} 

) 

) 

 

# iterate over data and extract the lines 

for line in data[1:]: 

if evaluate(line, cls_idx, family): 

lang = line[0].strip() 

wls = line[1].strip() 

wls_gen = line[2].strip() 

eth = line[3].strip() 

hh = line[4].strip() 

try: 

lat = float(line[5].replace(',', '.')) 

lng = float(line[6].replace(',', '.')) 

except: 

lat = '' 

lng = '' 

pop = int(line[7]) if line[7] else -10 

iso = line[9].strip() 

 

# check for population 

if min_population(pop): # >= min_population: 

# append data to meta 

if lang not in meta['coords']: 

meta["coords"][lang] = (lat, lng) 

meta["classification"]["hammarstroem"][lang] = hh 

meta["classification"]["wals"][lang] = wls 

meta["classification"]["wals_genus"][lang] = wls_gen 

meta["classification"]["ethnologue"][lang] = eth 

meta["population"][lang] = pop 

meta["iso"][lang] = iso 

 

for i, items in enumerate(line[10:], 10): 

item = header[i].strip() 

entries = [e.strip() for e in line[i].split(',') if 

e.strip() and 'xxx' not in e.lower()][:max_synonyms] 

 

for entry in entries: 

if entry.startswith('%'): 

entry = entry[1:] 

loan = 1 

else: 

loan = 0 

if ' ' in entry: 

entry = entry.replace(' ', '_') 

tokens = ' '.join(asjp2tokens(entry)) 

D[idx] = [lang, item, entry, tokens.split(' '), loan] 

idx += 1 

D[0] = ['doculect', 'concept', 'counterpart', 'tokens', 'known_borrowings'] 

D['meta'] = meta 

return D