• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[日常]Go语言圣经--Map习题

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

练习 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)函数,这样可以按单词而不是按行输入。
*/

  

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go覆盖测试工具介绍发布时间:2022-07-10
下一篇:
golangnoGofiles发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap