时间:2021-05-22
给定一篇英语文章,要求统计出所有单词的个数,并按一定次序输出。思路是利用go语言的map类型,以每个单词作为关键字存储数量信息,代码实现如下:
package main
import ( "fmt" "sort")func wordCounterV1(str string) { stringSlice := str[:] temp := str[:] wordStatistic := make(map[string]int) j := 0 for i := 0; i < len(stringSlice); i++ { if !((stringSlice[i] >= 65 && stringSlice[i] <= 90) || (stringSlice[i] >= 97 && stringSlice[i] <= 122)) { temp = str[j:i] if len(temp) != 0 { wordStatistic[temp]++ } j = i + 1 } } for i := range wordStatistic { if len(i) > 1 { if (i[0] >= 65 && i[0] <= 90) && (i[1] <= 65 || i[1] >= 90) { strTemp := make([]byte, len(i), len(i)) copy(strTemp, i) strTemp[0] += 32 wordStatistic[string(strTemp)] += wordStatistic[i] delete(wordStatistic, i) } } else { if i[0] != 'a' && i[0] != 'A' { delete(wordStatistic, i) } else if i[0] == 'A' { wordStatistic["a"] += wordStatistic[i] delete(wordStatistic, i) } } } sortSlice := make([]string, 0, len(wordStatistic)) for i := range wordStatistic { sortSlice = append(sortSlice, i) } sort.Strings(sortSlice) for _, v := range sortSlice { fmt.Printf("%s:%d\n", v, wordStatistic[v]) } fmt.Printf("word count:%d\n", len(wordStatistic))}主函数随便输入一篇英语文章
编译后终端输出结果:
C:\Users\24213\go project>cd src\github.com\go-study\lesson6\practice1C:\Users\24213\go project\src\github.com\go-study\lesson6\practice1>go buildC:\Users\24213\go project\src\github.com\go-study\lesson6\practice1>practice1a:4all:1along:1always:2and:8another:1appreciate:2are:2around:2bad:1based:1be:3because:1begins:1best:1born:1brighten:1brighter:1brightest:1can:2chance:1comes:1cry:1crying:2day:1die:1do:2don:3down:1dream:2dreams:1ends:1enough:4everyone:2everything:2failures:1feel:1for:3forgotten:1friendship:1from:1future:1go:4grows:1happen:1happiest:1happiness:2happy:1have:7heartaches:1hope:1hug:1human:1hurt:1hurts:2if:2importance:1in:4is:2it:3just:3keep:1kiss:1know:1let:2lies:1life:5live:1lives:1love:1make:6may:1mean:1message:2miss:2moments:1most:1much:1necessarily:1need:1nothing:1of:6on:3one:4only:2opportunity:1or:1other:1others:1out:1past:2people:3person:1pick:1please:1probably:1put:1re:1real:1really:2searched:1see:1send:1shoes:1side:1smile:2smiling:2so:2someone:2something:1sorrow:1strong:1sweet:1tear:1that:6the:10their:3them:3there:1they:2things:2this:2those:9to:19too:1touched:2trials:1tried:1until:1want:6was:1way:2well:1were:2what:2when:5where:1who:10will:3with:4worry:1you:32your:4yourself:1word count:144总结
以上所述是小编给大家介绍的go语言之给定英语文章统计单词数量(go语言小练习),希望对大家有所帮助!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
前言之前有一篇介绍如何使用Go语言通过SSH协议来执行远程命令:如何使用Go语言实现远程执行命令同样,通过SSH协议也可以使用Go语言来远程传输文件。除了SSH
一.GO语言开发包1.什么是GO语言开发包go语言开发包其实是对go语言的一种实现,包括相应版本的语法,编译,运行,垃圾回收等,里面包含着开发go语言所需的标准
Go语言是一个开源的,为创建简单的,快速的,可靠的软件而设计的语言。Go语言实(示)例教程,通过过实例加注释的方式来介绍Go语言的用法。HelloWorld第一
Go语言编辑器JetBrainsGoLand2021最新版是目前JetBrains针对go语言开发的最新GO语言编程工具,工具十分的好用,集成了非常不错的功能,
Go(又称Golang)是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。下载Go语言开发包 大家可以在Go语言官网(http