【发布时间】:2015-01-11 08:34:26
【问题描述】:
我正在写一个小程序来给段落编号:
- 在每段前面加上段号,形式为[1]...,[2]....
- 应排除文章标题。
这是我的程序:
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("\n") {
fmt.Printf("\n[%s]", p_num)
p_num += 1
} else {
fmt.Printf(char)
}
}
}
http://play.golang.org/p/f4S3vQbglY
我收到了这个错误:
prog.go:21: cannot convert "\n" to type byte
prog.go:21: cannot convert "\n" (type string) to type byte
prog.go:21: invalid operation: char == "\n" (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]
如何将字符串转换为字节?
处理文本的一般做法是什么?读入,按字节解析,还是按行解析?
更新
我通过将缓冲区字节转换为字符串,用正则表达式替换字符串来解决了这个问题。 (感谢@Tomasz Kłak 的正则表达式帮助)
我把代码放在这里供参考。
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("(\r\n)+")
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))
}
【问题讨论】:
-
使用单引号
'\n'而不是双引号"\n"来表示一个字节。此外,您的Printf应该有一个格式化字符串。见`play.golang.org/p/4DIjm6-N32
标签: go