我正在学习 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/