-
Notifications
You must be signed in to change notification settings - Fork 0
/
read_data.py
43 lines (40 loc) · 1.72 KB
/
read_data.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
# Copyright 2013 Philip N. Klein
from vec import Vec
from mat import Mat
def read_vectors(filename):
"""File should have the following format:
First line should consist of labels, separated by tabs or spaces.
Remaining lines should consist of numeric data.
Procedure returns a list of Vecs, one for each line of numeric data.
The labels for the Vecs are the strings given in the first line.
"""
with open(filename) as file:
labels = file.readline().split()
vlist = [Vec(set(labels), dict(zip(labels, map(float, line.split())))) for line in file]
return vlist
def read_matrix(filename):
"""File should have the following format:
First line should consist of column labels, separated by tabs or spaces.
Each subsequent line should consist of a row label followed by numeric data.
Procedure returns a matrix with the given row and column labels and numeric data
"""
with open(filename) as file:
col_labels = file.readline().split()
row_labels = set()
f = {}
for line in file:
entries = line.split()
row_label = entries[0]
row_labels.add(row_label)
for col, entry in zip(col_labels, entries[1:]):
f[row_label, col] = entry
return Mat((row_labels, set(col_labels)), f)
def read_vector(filename):
"""File should have the following format:
Each line consists of a label followed by a single numeric value, separated by whitespace
Procedure returns a vector with one entry per line of the file
"""
with open(filename) as file:
func = {k: float(v) for k,v in (line.split() for line in file)}
domain = set(func.keys())
return Vec(domain, func)