python - 戈朗 : read file generator

标签 python go generator

我正在学习 go 语言并尝试使用 golang 重写我的一些 Python 代码。 我编写了一个生成器函数,它逐行读取文本文件并仅发送(使用 yield 关键字)“有效”行(忽略空白行,重新组合未完成的行)。

示例文件 (myfile.txt):

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

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

解析.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) 

显示:

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

现在,我尝试使用 golang 中的闭包以相同的方式执行此操作:

解析.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)
    }
}

显示:

#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');
...

在 golang 中正确的做法是什么?

最佳答案

在 Go 中你可以使用 channels 而不是 yield,非常方便。

主要包

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

func ValidLines(filename string) (c chan string) {
    c = make(chan string)
    buff := ""
    go func() {
        file, err := os.Open(filename)
        if err != nil {
            close(c)
            return
        }

        reader := bufio.NewReader(file)
        for {
            line, err := reader.ReadString('\n')
            if err != nil {
                close(c)
                return
            }
            line = strings.TrimSpace(line)
            if line == "" {
                continue
            }
            buff += line
            if line[len(line)-1] != ';' {
                continue
            }
            c <- buff
            buff = ""
        }
    }()
    return c
}

func main() {
    for line := range ValidLines("myfile.txt") {
        fmt.Println(line)
    }
}

关于python - 戈朗 : read file generator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37458080/

相关文章:

python - 如何修复自定义 conda 包的 conda UnsatisfiableError?

python - 确定多记录html形式的记录

python 从字典中获取唯一值

python - 你怎么知道github存储库是用于python 2还是python 3

go - 通过 switch 语句分配类型/创建结构

go - 接口(interface)具有相同的方法,但被认为是不同的

loops - 如果永远运行,ticker.C 是否会泄漏内存?

node.js - typescript 异步生成器,用于套接字

python - 如何打印生成器对象的产生值?

php - Laravel 生成器给出 : Cannot redeclare generatorFunction()