Golang字符串处理:如何移除首尾空行

Golang字符串处理:如何移除首尾空行 我有以下文本:

str := "
 

Maybe we should all just listen to
records and quit our jobs

— gach White —

AZ QUOTES

 

 "

并且想要移除所有空行。 我能够像这样移除段落中的空行:

str = strings.Replace(str, "\n\n", "\n", -1)
fmt.Println(str)

最终得到:

 
Maybe we should all just listen to
records and quit our jobs
— gach White —
AZ QUOTES




所以,开头仍然有几行空行,结尾也有几行空行,我该如何去掉它们?

在我的应用程序中,我试图从同一目录中的所有“png”文件中提取文本,并以美观的格式获取,到目前为止我的完整代码如下:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	_ "image/png"
)

func main() {
	var files []string

	root := "."
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if filepath.Ext(path) == ".png" {
			path = strings.TrimSuffix(path, filepath.Ext(path))
			files = append(files, path)
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
	for _, file := range files {
		fmt.Println(file)

		err = exec.Command(`tesseract`, file+".png", file).Run()
		if err != nil {
			fmt.Printf("Error: %s\n", err)
		} else {
			b, err := ioutil.ReadFile(file + ".txt") // just pass the file name
			if err != nil {
				fmt.Print(err)
			} else {
				str := string(b) // convert content to a 'string'
				str = strings.Replace(str, "\n\n", "\n", -1)
				fmt.Println(str) // print the content as a 'string'
			}
		}
	}

}

更多关于Golang字符串处理:如何移除首尾空行的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

我找到的解决方案如下:

func trimEmptyLines(b []byte) string {
	strs := strings.Split(string(b), "\n")
	str := ""
	for _, s := range strs {
		if len(strings.TrimSpace(s)) == 0 {
			continue
		}
		str += s + "\n"
	}
	str = strings.TrimSuffix(str, "\n")

	return str
}

调用方式如下:

str := trimEmptyLines(b)

更多关于Golang字符串处理:如何移除首尾空行的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


hyousef:

str := " Maybe we should all just listen to records and quit our jobs — gach White — AZ QUOTES "

你可以直接使用 TrimSpace 函数来移除空白行。

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := `


	Maybe we should all just listen to
	records and quit our jobs

	— gach White —

	AZ QUOTES





	`
	fmt.Println(strings.TrimSpace(str))

}

你可以使用 strings.TrimSpace() 函数来移除字符串首尾的所有空白字符(包括空行)。不过这会同时移除空格和制表符。如果只想移除空行,可以这样处理:

// 移除首尾空行
func trimEmptyLines(s string) string {
    lines := strings.Split(s, "\n")
    
    // 移除开头的空行
    for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
        lines = lines[1:]
    }
    
    // 移除结尾的空行
    for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
        lines = lines[:len(lines)-1]
    }
    
    return strings.Join(lines, "\n")
}

在你的代码中这样使用:

b, err := ioutil.ReadFile(file + ".txt")
if err != nil {
    fmt.Print(err)
} else {
    str := string(b)
    str = trimEmptyLines(str)
    str = strings.Replace(str, "\n\n", "\n", -1)
    fmt.Println(str)
}

或者更简洁的方式,使用正则表达式:

import "regexp"

func trimEmptyLines(s string) string {
    // 移除开头的空行
    re := regexp.MustCompile(`^\s*\n`)
    s = re.ReplaceAllString(s, "")
    
    // 移除结尾的空行
    re = regexp.MustCompile(`\n\s*$`)
    s = re.ReplaceAllString(s, "")
    
    return s
}

如果你想要移除所有连续的空行(包括中间的空行),可以这样:

func removeAllEmptyLines(s string) string {
    // 移除所有连续的空行,只保留一个换行符
    re := regexp.MustCompile(`\n\s*\n`)
    s = re.ReplaceAllString(s, "\n")
    
    // 移除首尾空行
    s = strings.TrimSpace(s)
    
    return s
}

在你的具体场景中,可以直接使用:

str := string(b)
str = strings.TrimSpace(str)  // 移除首尾所有空白字符
str = strings.Replace(str, "\n\n", "\n", -1)  // 处理中间的空行
fmt.Println(str)

strings.TrimSpace() 会移除字符串开头和结尾的所有空白字符,包括空格、制表符、换行符等,这应该能满足你的需求。

回到顶部