美文网首页深入浅出golangGolang 入门资料+笔记程序员
24. map字典测试用例(文字出现次数统计)

24. map字典测试用例(文字出现次数统计)

作者: 厚土火焱 | 来源:发表于2017-08-16 17:26 被阅读109次

    利用map实现字符串内文字出现次数的统计。
    编写一个测试用例,对文字计数函数的功能进行测试。
    测试通过,则打印文字出现次数的统计结果

    package main
    
    import (
        "fmt"
        "strings"
    )
    //测试调用
    func Test(f func(string) map[string]int) {
        ok := true
        for _, c := range testCases {
            got := f(c.in)
            if len(c.want) != len(got) {
                ok = false
            } else {
                for k := range c.want {
                    if c.want[k] != got[k] {
                        ok = false
                    }
                }
            }
            if !ok {
                fmt.Printf("FAIL\n f(%q) =\n  %#v\n want:\n  %#v",
                    c.in, got, c.want)
                break
            }
            fmt.Printf("PASS\n f(%q) = \n  %#v\n", c.in, got)
        }
    }
    
    //测试用例
    var testCases = []struct {
        in   string
        want map[string]int
    }{
        {"I am learning Go!", map[string]int{
            "I": 1, "am": 1, "learning": 1, "Go!": 1,
        }},
        {"The quick brown fox jumped over the lazy dog.", map[string]int{
            "The":  1, "quick": 1, "brown": 1, "fox": 1, "jumped": 1,
            "over": 1, "the": 1, "lazy": 1, "dog.": 1,
        }},
        {"I ate a donut. Then I ate another donut.", map[string]int{
            "I": 2, "ate": 2, "a": 1, "donut.": 2, "Then": 1, "another": 1,
        }},
        {"A man a plan a canal panama.", map[string]int{
            "A": 1, "man": 1, "a": 2, "plan": 1, "canal": 1, "panama.": 1,
        }},
    }
    //文字出现次数统计
    func WordCount(s string) map[string]int {
        s0 := strings.Fields(s)
    
        s1 := make(map[string]int)
        for _, k := range s0 {
            _, ok := s1[k]
            if !ok {
                s1[k] = 1
            }else{
                s1[k] += 1
            }
        }
    
        return s1
        //return map[string]int{"x": 1}
    }
    
    func main() {
        Test(WordCount)
    }
    
    

    WordCount实现文字次数统计
    s0是对原来句子中的文字建立切片
    s1是统计后的结果map,每个文字都是一个键
    运行效果

    PASS
     f("I am learning Go!") = 
      map[string]int{"I":1, "am":1, "learning":1, "Go!":1}
    PASS
     f("The quick brown fox jumped over the lazy dog.") = 
      map[string]int{"brown":1, "the":1, "jumped":1, "over":1, "lazy":1, "dog.":1, "The":1, "quick":1, "fox":1}
    PASS
     f("I ate a donut. Then I ate another donut.") = 
      map[string]int{"ate":2, "a":1, "donut.":2, "Then":1, "another":1, "I":2}
    PASS
     f("A man a plan a canal panama.") = 
      map[string]int{"A":1, "man":1, "a":2, "plan":1, "canal":1, "panama.":1}
    

    相关文章

      网友评论

        本文标题:24. map字典测试用例(文字出现次数统计)

        本文链接:https://www.haomeiwen.com/subject/lxwirxtx.html