dqls67891 2014-07-05 16:16
浏览 24
已采纳

执行:从字符串中删除重音

I'm new to Go and I'm trying to implement a function to convert accented characters into their non-accented equivalent. I'm attempting to follow the example given in this blog (see the heading 'Performing magic').

What I've attempted to gather from this is:

package main

import (
    "fmt"
    "unicode"
    "bytes"
    "code.google.com/p/go.text/transform"
    "code.google.com/p/go.text/unicode/norm"
)


func isMn (r rune) bool {
        return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
    }

func main() {
    r := bytes.NewBufferString("Your Śtring")
    t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
    r = transform.NewReader(r, t)
    fmt.Println(r)
}

It does not work in the slightest and I quite honestly don't know what it means anyway. Any ideas?

  • 写回答

2条回答 默认 最新

  • dqj5046 2014-07-05 17:59
    关注

    r should be or type io.Reader, and you can't print r like that. First, you need to read the content to a byte slice:

     var (   
             s = "Your Śtring"
             b = make([]byte, len(s))
    
             r io.Reader = strings.NewReader(s)
     ) 
     t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
     r = transform.NewReader(r, t)
     r.Read(b)
     fmt.Println(string(b))
    

    This works, but for some reason it returns me "Your Stri", two bytes less than needed.

    This here is the version which actually does what you need, but I'm still not sure why the example from the blog works so strangely.

    s := "Yoùr Śtring"
    b := make([]byte, len(s))
    
    t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
    _, _, e := t.Transform(b, []byte(s), true)
    if e != nil { panic(e) }
    
    fmt.Println(string(b))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制