donglie1994 2012-12-09 17:36
浏览 173
已采纳

读取一个文本文件,替换其单词,输出到另一个文本文件

So I am trying to make a program in GO to take a text file full of code and convert that into GO code and then save that file into a GO file or text file. I have been trying to figure out how to save the changes I made to the text file, but the only way I can see the changes is through a println statement because I am using strings.replace to search the string array that the text file is stored in and change each occurrence of a word that needs to be changed (ex. BEGIN -> { and END -> }). So is there any other way of searching and replacing in GO I don't know about or is there a way to edit a text file that I don't know about or is this impossible?

Thanks

Here is the code I have so far.

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) + "
");

        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
", 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
", errr)
        return
    }
    errr = writeLines(lines, "beer2.txt")
    fmt.Println(errr)
}
  • 写回答

2条回答 默认 最新

  • dongwa3808 2012-12-09 17:55
    关注
    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$ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)