如何提高G中的文件编码转换

2024-06-01 06:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在处理一些需要转换成UTF-8的大文件,因为像iconv这样的传统工具无法使用这些文件。所以我决定在Go中编写自己的工具,但是我注意到这种编码转换在Go中相当慢。这是我的密码:

package main

import (
    "fmt"
    "io"
    "log"
    "os"

    "golang.org/x/text/encoding/charmap"
)

func main() {
    if len(os.Args) != 3 {
        fmt.Fprintf(os.Stderr, "usage:\n\t%s [input] [output]\n", os.Args[0])
        os.Exit(1)
    }

    f, err := os.Open(os.Args[1])

    if err != nil {
        log.Fatal(err)
    }

    out, err := os.Create(os.Args[2])

    if err != nil {
        log.Fatal(err)
    }

    r := charmap.ISO8859_1.NewDecoder().Reader(f)

    buf := make([]byte, 1048576)

    io.CopyBuffer(out, r, buf)

    out.Close()
    f.Close()
}

Python中的类似代码的性能要高得多:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open("FRWAC-01.xml", "r", "latin_1") as sourceFile:
    with codecs.open("FRWAC-01-utf8.xml", "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

我确信我的Go代码会快得多,因为一般来说,Go中的I/O速度很快,但事实证明它比Python代码慢得多。有没有办法改进围棋项目?你知道吗


Tags: 文件工具代码importloggoifos
1条回答
网友
1楼 · 发布于 2024-06-01 06:17:48

这里的问题是,在这两种情况下,您没有比较相同的代码。此外,Go中的IO速度与python没有太大区别,因为它们进行相同的系统调用。你知道吗

在python版本中,默认情况下会缓冲文件。在Go版本中,当您将io.CopyBuffer1048576字节缓冲区一起使用时,解码器将直接对无缓冲区文件进行所需大小的Read调用。你知道吗

bufio包装文件IO将产生类似的结果。你知道吗

inFile, err := os.Open(os.Args[1])
if err != nil {
    log.Fatal(err)
}
defer inFile.Close()

outFile, err := os.Create(os.Args[2])
if err != nil {
    log.Fatal(err)
}
defer outFile.Close()

in := bufio.NewReaderSize(inFile, 1<<20)

out := bufio.NewWriterSize(outFile, 1<<20)
defer out.Flush()

r := charmap.ISO8859_1.NewDecoder().Reader(in)

if _, err := io.Copy(out, r); err != nil {
    log.Fatal(err)
}

相关问题 更多 >