douyu7879 2016-05-26 10:23
浏览 70
已采纳

golang:读取文件生成器

I'm learning go language and try to rewrite some of my Python code using golang. I wrote a generator function that reads a text file line by line and send (using yield keyword) only "valid" lines (blank lines are ignored, uncompleted lines are recomposed).

Sample file (myfile.txt):

#123= FOOBAR(1.,'text');

#126= BARBAZ('poeazpfodsp',
234,56);

parse.py:

#!/usr/bin/python
def validlines(filename):
    with open(filename) as fdin:
        buff = ''
        for line in fdin.readlines():
            line = line.strip()
            if line == '':
                continue
            buff += line
            if line[-1] != ';':
                continue
            yield buff
            buff = ''
        fdin.close()

for line in validlines('myfile.txt'):
    print(line) 

displays:

#123= FOOBAR(1.,'text');
#126= BARBAZ('poeazpfodsp',234,56);    

Now, I try to do it the same way using a closure in golang:

parse.go:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func validLines(filename string) (func() (string, bool)) {

    file, _ := os.Open(filename)
    scanner := bufio.NewScanner(file)

    return func() (string, bool) {
        buff := ""
        for scanner.Scan() {
            line := scanner.Text()
            line = strings.TrimSpace(line)

            if line == "" {
                continue
            }
            buff += line
            if line[len(line)-1] != ';' {
                continue
            }
            return buff, true
        }

        file.Close()
        return "", false
    }
}

func main() {
    vline := validLines("myfile.txt")
    for line, ok := vline(); ok; {
        fmt.Println(line)
    }
}

displays:

#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
#123= FOOBAR(1.,'text');
...

What's the right way to do it in golang?

  • 写回答

4条回答 默认 最新

  • dongmou1964 2016-05-26 10:40
    关注

    This is the for loop of your main which is the problem. With this syntax, here is what it does:

    1. Initialize line and ok with a first call to vline()
    2. If ok is true, run the loop once
    3. Update something at the end of the block, and go to 2.

    So, your problem is that you never update lineand ok. Here is the correct version:

    for line, ok := vline(); ok; line, ok = vline() { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格