dourang6423 2015-01-11 08:34
浏览 46
已采纳

Go中的文本处理-如何将字符串转换为字节?

I'm writing a small pragram to number the paragraph:

  1. put paragraph number in front of each paragraph in the form of [1]..., [2]....
  2. Article title should be excluded.

Here is my program:

package main

import (
    "fmt"
    "io/ioutil"
)

var s_end = [3]string{".", "!", "?"}

func main() {
    b, err := ioutil.ReadFile("i_have_a_dream.txt")
    if err != nil {
        panic(err)
    }

    p_num, s_num := 1, 1

    for _, char := range b {
        fmt.Printf("[%s]", p_num)
        p_num += 1
        if char == byte("
") {
            fmt.Printf("
[%s]", p_num)
            p_num += 1
        } else {
            fmt.Printf(char)
        }
    }
}

http://play.golang.org/p/f4S3vQbglY

I got this error:

prog.go:21: cannot convert "
" to type byte
prog.go:21: cannot convert "
" (type string) to type byte
prog.go:21: invalid operation: char == "
" (mismatched types byte and string)
prog.go:25: cannot use char (type byte) as type string in argument to fmt.Printf
[process exited with non-zero status]

How to convert string to byte?

What is the general practice to process text? Read in, parse it by byte, or by line?

Update

I solved the problem by converting the buffer byte to string, replacing strings by regular expression. (Thanks to @Tomasz Kłak for the regexp help)

I put the code here for reference.

package main

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


func main() {
    b, err := ioutil.ReadFile("i_have_a_dream.txt")
    if err != nil {
        panic(err)
    }

    s := string(b)
    r := regexp.MustCompile("(
)+")
    counter := 1

    repl := func(match string) string {
        p_num := counter
        counter++
        return fmt.Sprintf("%s [%d] ", match, p_num)
    }

    fmt.Println(r.ReplaceAllStringFunc(s, repl))
}
  • 写回答

2条回答 默认 最新

  • dongzhenju3015 2015-01-11 08:40
    关注

    Using " " causes it to be treated as an array, use ' ' to treat it as a single char.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿