4

所以我试图在 GO 中制作一个程序来获取一个充满代码的文本文件并将其转换为 GO 代码,然后将该文件保存到 GO 文件或文本文件中。我一直在试图弄清楚如何保存我对文本文件所做的更改,但我可以看到更改的唯一方法是通过 println 语句,因为我正在使用 strings.replace 来搜索文本文件所在的字符串数组存储并更改每次出现的需要更改的单词(例如 BEGIN -> { 和 END -> })。那么在我不知道的 GO 中是否有任何其他搜索和替换方式,或者有没有办法编辑我不知道的文本文件,或者这是不可能的?

谢谢

这是我到目前为止的代码。

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)


func readLines(path string) (lines []string, errr error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, errr = os.Open(path); errr != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, errr = reader.ReadLine(); errr != nil {
            break
        }
    buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if errr == io.EOF {
        errr = nil
    }
    return
}

func writeLines(lines []string, path string) (errr error) {
    var (
        file *os.File
    )

    if file, errr = os.Create(path); errr != nil {
        return
    }
    defer file.Close()


    for _,item := range lines {

        _, errr := file.WriteString(strings.TrimSpace(item) + "\n");

        if errr != nil {

            fmt.Println(errr)
            break
        }
    }

    return
}

func FixBegin(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "BEGIN", "{", -1))
    }

    return
}

func FixEnd(lines []string) (errr error) {
    var(
    a string

    )
for i := 0; ; i++ {
        a = lines[i];

        fmt.Println(strings.Replace(a, "END", "}", -1))
    }
    return
}

func main() {
    lines, errr := readLines("foo.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }


    errr = FixBegin(lines)

    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)

    errr = FixEnd(lines)
    lines, errr = readLines("beer2.txt")
    if errr != nil {
        fmt.Println("Error: %s\n", errr)
        return
    }
    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)
}
4

3 回答 3

3
jnml@fsc-r630:~/src/tmp/SO/13789882$ ls
foo.txt  main.go
jnml@fsc-r630:~/src/tmp/SO/13789882$ cat main.go 
package main

import (
        "bytes"
        "io/ioutil"
        "log"
)

func main() {
        src, err := ioutil.ReadFile("foo.txt")
        if err != nil {
                log.Fatal(err)
        }

        src = bytes.Replace(src, []byte("BEGIN"), []byte("{"), -1)
        src = bytes.Replace(src, []byte("END"), []byte("}"), -1)
        if err = ioutil.WriteFile("beer2.txt", src, 0666); err != nil {
                log.Fatal(err)
        }
}
jnml@fsc-r630:~/src/tmp/SO/13789882$ cat foo.txt 
BEGIN
  FILE F(KIND=REMOTE);
  EBCDIC ARRAY E[0:11];
  REPLACE E BY "HELLO WORLD!";
  WRITE(F, *, E);
END.
jnml@fsc-r630:~/src/tmp/SO/13789882$ go run main.go 
jnml@fsc-r630:~/src/tmp/SO/13789882$ cat beer2.txt 
{
  FILE F(KIND=REMOTE);
  EBCDIC ARRAY E[0:11];
  REPLACE E BY "HELLO WORLD!";
  WRITE(F, *, E);
}.
jnml@fsc-r630:~/src/tmp/SO/13789882$ 
于 2012-12-09T17:55:48.673 回答
3

我同意@jnml wrt 使用 ioutil 啜食文件并将其写回。但我认为替换不应该通过多次传递[]byte来完成。代码和数据是字符串/文本,应该这样对待(即使处理非 ascii/utf8 编码需要 estra 工作);一次性替换(所有占位符“一次”)避免了替换先前更改结果的风险(即使我的正则表达式提案必须改进以处理非平凡的任务)。

package main

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

func main() {
    // (1) slurp the file
    data, err := ioutil.ReadFile("../tmpl/xpl.go")
    if err != nil {
        log.Fatal("ioutil.ReadFile: ", err)
    }
    s := string(data)
    fmt.Printf("----\n%s----\n", s)
    // => function that works for files of (known) other encodings that ascii or utf8

    // (2) create a map that maps placeholder to be replaced to the replacements
    x := map[string]string {
        "BEGIN" : "{",
        "END" : "}"}
    ks := make([]string, 0, len(x))
    for k := range x {
        ks = append(ks, k)
    }
    // => function(s) that gets the keys from maps

    // (3) create a regexp that finds the placeholder to be replaced
    p := strings.Join(ks, "|")
    fmt.Printf("/%s/\n", p)
    r := regexp.MustCompile(p)
    // => funny letters & order need more consideration

    // (4) create a callback function for ..ReplaceAllStringFunc that knows
    // about the map x
    f := func(s string) string {
        fmt.Printf("*** '%s'\n", s)
        return x[s]
    }
    // => function (?) to do Step (2) .. (4) in a reusable way

    // (5) do the replacing (s will be overwritten with the result)
    s = r.ReplaceAllStringFunc(s, f)
    fmt.Printf("----\n%s----\n", s)

    // (6) write back
    err = ioutil.WriteFile("result.go", []byte(s), 0644)
    if err != nil {
        log.Fatal("ioutil.WriteFile: ", err)
    }
    // => function that works for files of (known) other encodings that ascii or utf8
}

输出:

go run 13789882.go
----
func main() BEGIN
END
----
/BEGIN|END/
*** 'BEGIN'
*** 'END'
----
func main() {
}
----
于 2012-12-09T20:03:15.467 回答
1

如果您的文件很大,则可能无法也不建议读取内存中的所有内容。试一试BytesReplacingReader,因为它以流媒体方式完成替换。而且它的性能相当不错。如果你想替换两个字符串(例如BEGIN -> {and END -> }),只需要BytesReplacingReader在原始阅读器上包裹两个,一个 forBEGIN和一个 for END

r := NewBytesReplacingReader(
    NewBytesReplacingReader(inputReader, []byte("BEGIN"), []byte("{"),
    []byte("END"), []byte("}")
// use r normally and all non-overlapping occurrences of
// "BEGIN" and "END" will be replaced with "{" and "}"
于 2020-06-01T01:15:43.610 回答