Golang中如何从输入文件中移除空行
Golang中如何从输入文件中移除空行 我想从我的 input.txt 文件中移除空行,并将每个组(即第一行、第二行、第三行)存储在一个单独的数组切片中,以便计算各个组中的成员数量。
Input.txt 第一行 第一行
第二行 第二行 第二行 第二行
第三行 第三行 第三行
3 回复
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
var lines [][]string
f, err := os.Open(`Input.txt`)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
newLine := true
for s.Scan() {
line := strings.TrimSpace(s.Text())
if len(line) == 0 {
newLine = true
continue
}
if newLine {
newLine = false
lines = append(lines, make([]string, 0))
}
last := len(lines) - 1
lines[last] = append(lines[last], line)
}
if err := s.Err(); err != nil {
fmt.Println(err)
return
}
for _, line := range lines {
fmt.Println(len(line), ":", strings.Join(line, " || "))
}
}
.
2 : First line || First line
4 : Second line || Second line || Second line || Second line
3 : Third line || Third line || Third line
在Golang中,你可以通过以下方式从输入文件中移除空行,并将每个组存储到单独的切片中:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// 打开文件
file, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer file.Close()
// 创建扫描器读取文件
scanner := bufio.NewScanner(file)
// 存储所有组的切片
var groups [][]string
// 当前组的临时存储
var currentGroup []string
for scanner.Scan() {
line := scanner.Text()
// 检查是否为空行
if line == "" {
// 如果当前组有内容,则添加到groups中
if len(currentGroup) > 0 {
groups = append(groups, currentGroup)
currentGroup = []string{}
}
continue
}
// 将非空行添加到当前组
currentGroup = append(currentGroup, line)
}
// 处理文件末尾的最后一个组
if len(currentGroup) > 0 {
groups = append(groups, currentGroup)
}
// 检查扫描错误
if err := scanner.Err(); err != nil {
panic(err)
}
// 输出结果
for i, group := range groups {
fmt.Printf("Group %d (成员数量: %d):\n", i+1, len(group))
for _, line := range group {
fmt.Printf(" %s\n", line)
}
}
}
这段代码会:
- 读取input.txt文件
- 跳过所有空行
- 将连续的非空行分组存储
- 每个组存储在一个单独的切片中
- 最后输出每个组的成员数量
输出结果示例:
Group 1 (成员数量: 2):
第一行
第一行
Group 2 (成员数量: 4):
第二行
第二行
第二行
第二行
Group 3 (成员数量: 3):
第三行
第三行
第三行
如果你需要单独访问每个组,可以通过groups[0]、groups[1]、groups[2]来获取对应的切片。

