[日常] Go语言圣经--Map习题
2023-02-18 15:47:09 时间
练习 4.8: 修改charcount程序,使用unicode.IsLetter等相关的函数,统计字母、数字等Unicode中不同的字符类别。
练习 4.9: 编写一个程序wordfreq程序,报告输入文本中每个单词出现的频率。在第一次调用Scan前先调用input.Split(bufio.ScanWords)函数,这样可以按单词而不是按行输入。
// Charcount computes counts of Unicode characters. package main import ( "bufio" "fmt" "io" "os" "unicode" "unicode/utf8" ) func main() { //counts := make(map[string]map[rune]int) // counts of Unicode characters var utflen [utf8.UTFMax + 1]int // count of lengths of UTF-8 encodings invalid := 0 // count of invalid UTF-8 characters letters := make(map[rune]int) numbers := make(map[rune]int) in := bufio.NewReader(os.Stdin) for { r, n, err := in.ReadRune() // returns rune, nbytes, error if err == io.EOF { break } if err != nil { fmt.Fprintf(os.Stderr, "charcount: %v\n", err) os.Exit(1) } if r == unicode.ReplacementChar && n == 1 { invalid++ continue } /* 练习 4.8: 修改charcount程序,使用unicode.IsLetter等相关的函数,统计字母、数字等Unicode中不同的字符类别。 */ //判断是字母 if unicode.IsLetter(r){ letters[r]++ } //判断是数字 if unicode.IsNumber(r){ numbers[r]++ } //counts[r]++ utflen[n]++ } fmt.Printf("rune\tcount\n") for c, n := range letters { fmt.Printf("%q\t%d\n", c, n) } fmt.Printf("rune(number)\tcount\n") for c, n := range numbers { fmt.Printf("%q\t%d\n", c, n) } fmt.Print("\nlen\tcount\n") for i, n := range utflen { if i > 0 { fmt.Printf("%d\t%d\n", i, n) } } if invalid > 0 { fmt.Printf("\n%d invalid UTF-8 characters\n", invalid) } }
package main import ( "bufio" "fmt" //"io" "os" //"unicode" //"unicode/utf8" ) func main() { counts := make(map[string]int) input := bufio.NewScanner(os.Stdin) input.Split(bufio.ScanWords) for input.Scan(){ counts[input.Text()]++ } for k,v :=range counts{ fmt.Printf("%s == %d \n",k,v) } } /* 练习 4.9: 编写一个程序wordfreq程序,报告输入文本中每个单词出现的频率。在第一次调用Scan前先调用input.Split(bufio.ScanWords)函数,这样可以按单词而不是按行输入。 */
相关文章
- [Go] golang调用第三方smtp发送邮件
- [Go]当把json解析到interface{}时 , 对应的真正类型
- [Go] 利用类型断言把interface{}的转换回原类型
- [linux] du查找数据大的目录
- [Go] template显示html不要被转码
- [Go] golang获取http中的get传递的参数
- [Go] golang读取打包html文件到二进制
- [Go] golang http下返回json数据
- [Go] Golang练习项目-邮箱imap网页版客户端工具
- [Go] 提供http服务出现两次请求以及处理favicon.ico
- [Go] 转换编码处理网页显示乱码
- [Go] go转换gbk为utf8
- [Go] golang获取程序执行的绝对路径
- [Go] golang x.(type) 用法
- [linux] 查看centos或ubuntu的系统版本
- [GO] go语言中结构体的三种初始化方式
- [Git] 彻底删除github上的某个文件以及他的提交历史
- [linux] centos系统yum安装rz与sz
- [GO]golang实现AES加解密
- [GO] 解决:crypto/aes: invalid key size 14