Perhaps, something like this?
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"time"
)
type Match struct {
Date time.Time
Opponents string
Venue string
Type string
Result string
Scorers string
Attendance string
}
var fmtMatchDate = "Mon 02 Jan 2006"
func (m Match) String() string {
var s string
s += fmt.Sprint(m.Date.Format(fmtMatchDate), "
")
s += fmt.Sprint(
m.Opponents, "
",
m.Venue, "
",
m.Type, "
",
m.Result, "
",
)
if len(m.Scorers) > 0 {
s += fmt.Sprint(
m.Scorers, "
",
)
}
if len(m.Attendance) > 0 {
s += fmt.Sprint(
m.Attendance, "
",
)
}
return s
}
func ParseMatch(lines []string) (Match, error) {
// TODO: Implement a better parser.
var m Match
for i, line := range lines {
line = strings.TrimSpace(line)
switch i {
case 0:
date, err := time.Parse(fmtMatchDate, line)
if err != nil {
return Match{}, err
}
m.Date = date
case 1:
m.Opponents = line
case 2:
m.Venue = line
case 3:
m.Type = line
case 4:
m.Result = line
case 5:
m.Scorers = line
case 6:
m.Attendance = line
default:
}
}
return m, nil
}
func main() {
f, err := os.Open("match.txt")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var lines []string
snr := bufio.NewScanner(f)
for snr.Scan() {
line := snr.Text()
if _, err = time.Parse(fmtMatchDate, strings.TrimSpace(line)); err == nil {
if len(lines) > 0 {
m, err := ParseMatch(lines)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
fmt.Print(m)
}
}
lines = lines[:0]
}
lines = append(lines, line)
}
if len(lines) > 0 {
m, err := ParseMatch(lines)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
fmt.Print(m)
}
}
if err := snr.Err(); err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
}
Input:
$ cat match.txt
Sat 08 Aug 2015
Norwich City
A
League
W 3-1
Zaha 38; Delaney 48; Cabaye 90
27,036
Sun 16 Aug 2015
Arsenal
H
League
L 1-2
Sat 29 Aug 2015
Chelsea
A
League
W 2-1
Sako 64; Ward 80
41,581
Output:
$ go run match.go
Sat 08 Aug 2015
Norwich City
A
League
W 3-1
Zaha 38; Delaney 48; Cabaye 90
27,036
Sun 16 Aug 2015
Arsenal
H
League
L 1-2
Sat 29 Aug 2015
Chelsea
A
League
W 2-1
Sako 64; Ward 80
41,581
$