This repository has been archived by the owner on Oct 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
122 lines (108 loc) · 2.26 KB
/
convert.go
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
package convert
import (
"bufio"
"encoding/csv"
"log"
"os"
"regexp"
"strings"
)
type parsed struct {
answer string
attempts string
}
func parseCodioJoin(val string, postfix string) map[string]string {
ret := make(map[string]string)
scanner := bufio.NewScanner(strings.NewReader(val))
header := ""
body := ""
nameMatch, err := regexp.Compile(`^.*?:$`)
if err != nil {
log.Fatal(err)
}
for scanner.Scan() {
text := scanner.Text()
if nameMatch.MatchString(text) {
if len(header) > 0 {
ret[header] = body
}
header = strings.TrimSuffix(text, ":") + postfix
header = strings.ReplaceAll(header, "_", " ")
body = ""
} else {
body = body + text + "\n"
}
}
if len(header) > 0 {
ret[header] = body
}
return ret
}
func getKeys(val map[string]string) []string {
keys := make([]string, 0, len(val))
for k := range val {
keys = append(keys, k)
}
return keys
}
func join(record []string, keysMap []string, values map[string]string) []string {
for _, v := range keysMap {
value, ok := values[v]
if !ok {
value = ""
}
record = append(record, value)
}
return record
}
func uniq(s []string) []string {
m := make(map[string]bool)
for _, item := range s {
m[item] = true
}
var result []string
for item := range m {
result = append(result, item)
}
return result
}
func Convert(srcFile string, dstFile string) {
f, err := os.Open(srcFile)
if err != nil {
log.Fatal(err)
}
in := csv.NewReader(f)
fOut, err := os.Create(dstFile)
if err != nil {
log.Fatal(err)
}
defer fOut.Close()
csvOut := csv.NewWriter(fOut)
defer csvOut.Flush()
header, err := in.Read() // read header
if err != nil {
log.Fatal(err)
}
records, err := in.ReadAll()
if err != nil {
log.Fatal(err)
}
var keys []string
for _, record := range records {
answers := parseCodioJoin(record[25], "_anwser")
attempts := parseCodioJoin(record[26], "_attempts")
keys = append(keys, getKeys(answers)...)
keys = append(keys, getKeys(attempts)...)
}
keys = uniq(keys)
header = append(header, keys...)
csvOut.Write(header)
for _, record := range records {
values := parseCodioJoin(record[25], "_anwser")
for k, v := range parseCodioJoin(record[26], "_attempts") {
values[k] = v
}
res := join(record, keys, values)
csvOut.Write(res)
}
}