读取 utf-8 并替换错误

huangapple go评论76阅读模式
英文:

Read utf-8 and replace errors

问题

在Go语言中,你可以使用类似的方式读取文件并替换错误字符。下面是一个示例代码:

package main

import (
	"fmt"
	"io/ioutil"
	"strings"
)

func main() {
	filename := "your_file.txt"
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}

	// 将错误字符替换为指定的字符(例如'?')
	content = []byte(strings.ReplaceAll(string(content), "\uFFFD", "?"))

	// 打印替换后的内容
	fmt.Println(string(content))
}

你可以将your_file.txt替换为你要读取的文件路径。这段代码会读取文件内容,并将错误字符替换为指定的字符(例如'?'),然后打印替换后的内容。

英文:

in python I can read a file in utf8 and replace any errors like this:

with open(filename, encoding='utf-8', errors='replace') as ifile:

Is there an equivalent for golang?

Thanks.

答案1

得分: 2

Python代码没有完全匹配的原因是Go文件将文件数据原样返回,没有解码步骤。

如果你的目标是修复无效的UTF-8序列,可以使用bytes.ToValidUTF8来修复从文件中读取的数据。

var unicodeReplacement = []byte{0xef, 0xbf, 0xbd}

func readFileFix(filename string) ([]byte, error) {
    p, err := os.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return bytes.ToValidUTF8(p, unicodeReplacement), nil
}
英文:

There's not an exact match for the Python code because Go files return the file data as is. There's no decoding step.

If your goal is fix invalid UTF-8 sequences, then use
bytes.ToValidUTF8 to fix data slurped up from the file.

var unicodeReplacement = []byte{0xef, 0xbf, 0xbd}

func readFileFix(filename string) ([]byte, error) {
	p, err := os.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return bytes.ToValidUTF8(p, unicodeReplacement), nil
}

huangapple
  • 本文由 发表于 2021年8月28日 04:54:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/68959272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定