douxi4114 2016-03-27 09:23 采纳率: 100%
浏览 469

使用golang从文件中提取数据

I am trying to extract lines from a file if a condition is met.

The data in the file look like this :

Sat 08 Aug 2015
Norwich City
A
League
    W 3-1
    Zaha 38; Delaney 48; Cabaye 90
    27,036

If the pattern of the date is matched, I want to print the following five lines.

My code is,

func main() {

    r, _ := regexp.Compile("[aA-zZ]{3}\\s[0-9]{2}\\s[aA-zZ]{3}\\s[0-9]{4}")

    file, err := os.Open("test.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {

        if r.MatchString(scanner.Text()) {

            fmt.Println(scanner.Text())

            // here how do i capture the following 5 lines

        }

        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
    }
}
  • 写回答

3条回答 默认 最新

  • dongtong7990 2016-03-27 15:49
    关注

    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
    $
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值