dourang6423 2015-01-11 00: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:

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. )
  6. var s_end = [3]string{".", "!", "?"}
  7. func main() {
  8. b, err := ioutil.ReadFile("i_have_a_dream.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. p_num, s_num := 1, 1
  13. for _, char := range b {
  14. fmt.Printf("[%s]", p_num)
  15. p_num += 1
  16. if char == byte("
  17. ") {
  18. fmt.Printf("
  19. [%s]", p_num)
  20. p_num += 1
  21. } else {
  22. fmt.Printf(char)
  23. }
  24. }
  25. }

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

I got this error:

  1. prog.go:21: cannot convert "
  2. " to type byte
  3. prog.go:21: cannot convert "
  4. " (type string) to type byte
  5. prog.go:21: invalid operation: char == "
  6. " (mismatched types byte and string)
  7. prog.go:25: cannot use char (type byte) as type string in argument to fmt.Printf
  8. [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.

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "regexp"
  6. )
  7. func main() {
  8. b, err := ioutil.ReadFile("i_have_a_dream.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. s := string(b)
  13. r := regexp.MustCompile("(
  14. )+")
  15. counter := 1
  16. repl := func(match string) string {
  17. p_num := counter
  18. counter++
  19. return fmt.Sprintf("%s [%d] ", match, p_num)
  20. }
  21. fmt.Println(r.ReplaceAllStringFunc(s, repl))
  22. }

展开全部

  • 写回答

2条回答 默认 最新

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

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

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

报告相同问题?

悬赏问题

  • ¥15 盘古气象大模型调用(python)
  • ¥15 传人记程序做的plc 485从机程序该如何写
  • ¥15 已知手指抓握过程中掌指关节、手指各关节和指尖每一帧的坐标,用贝塞尔曲线可以拟合手指抓握的运动轨迹吗?
  • ¥50 libwebsockets 如何添加其他socket事件回调
  • ¥50 实现画布拖拽算子排布,通过flink实现算子编排计算,请提供思路
  • ¥15 esium自定义材质拉伸问题
  • ¥15 cmake+mingw使用<mysqlx/xdevapi.h>报错
  • ¥15 eNSP中防火墙的使用
  • ¥15 关于#mlnet#的问题:mlnet相关请求(语言-c#)
  • ¥15 lvgl7.11怎么做出文字被选中的效果
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部