如何在 Go 中逐行处理文件?
时间:2024-04-16
浏览:123
作者:佚名
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《如何在 Go 中逐行处理文件?》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
问题内容
在这里,我尝试编写一个函数 findmajordifference(words),它从文件“words.txt”返回 10、11 和 12 字符串的单词。 k 字符串是字符串 b,其中任意一对不同字母(在字母表的圆形排列内)之间的距离大于 k。例如,
- “silk”是 1 串
- “oaks”是 3 串、2 串和 1 串。
在下面的代码中,我尝试将所有 10、11 和 12 字符串放入一个数组中,但我认为它有问题。我一直试图弄清楚我是否正确地逐行处理了文件。
package main
import (
"fmt"
"io/ioutil"
)
func findMajorDifference(words []byte) []string
{
alpha := "abcdefghijklmnopqrstuvwxyz"
major := []string{}
B := string(words)
distance := 0 // current distance between 2 distinct letters (pos1 - pos2)
min := 26 // smallest distance between 2 distinct letters
pos1 := 0 // position of first letter in the alpha array
pos2 := 0 // position of second letter in the alpha array
for i := 0; i < len(B); i++ {
current := B[i] // current letter
for x := 1; x < len(B); x++ {
next := B[x] // next distinct letter
if current != next {
// find position of letters
for j := 0; j < len(alpha); j++ {
if current == alpha[j] {
pos1 = j
}
}
for k := 0; k < len(alpha); k++ {
if next == alpha[k] {
pos2 = k
}
}
// find distance
if pos1 > pos2 {
distance = pos1 - pos2
} else {
distance = pos2 - pos1
}
if distance < min {
min = distance
}
}
}
if min == 11 || min == 12 || min == 13 {
major = append(major, string(B[i]))
}
}
return major
} // end of findMajorBinjai
func main()
{
words, err := ioutil.ReadFile("words.txt")
if err != nil {
fmt.Println("File reading error", err)
return
}
fmt.Println("test") // This line is printed
fmt.Println("%s", findMajorDifference(words)) // Gives no output
}
我的代码没有给出任何错误,但也没有打印我想要的输出。
解决方案
使用bufio.NewReader和Reader.ReadString
func GetFileReader(filePath string) *os.File {
path, err := filepath.Abs(filePath)
if err != nil {
panic(err)
}
inFile, err := os.Open(path)
if err != nil {
panic(errors.New(err.Error() + `: ` + path))
}
return inFile
}
func Read(r io.Reader) {
reader := bufio.NewReader(r)
for {
text, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
return
}
panic(err)
}
//your logic using text
}
}
func main() {
inFile := GetFileReader(filePath)
defer inFile.Close()
Read(inFile)
}今天关于《如何在 Go 中逐行处理文件?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
