frequency works
This commit is contained in:
parent
d8ea359d48
commit
925129f76e
3 changed files with 28 additions and 18 deletions
|
@ -1,3 +1,5 @@
|
|||
module frequency
|
||||
|
||||
go 1.18
|
||||
|
||||
require github.com/dariubs/percent v1.0.0
|
||||
|
|
2
Lab04/code/part01/go.sum
Normal file
2
Lab04/code/part01/go.sum
Normal file
|
@ -0,0 +1,2 @@
|
|||
github.com/dariubs/percent v1.0.0 h1:fY8q40FRYaCiFZ0gTOa73Cmp21hS32w+tSSmqbGnUzc=
|
||||
github.com/dariubs/percent v1.0.0/go.mod h1:NDZpkezJ8QqyIW/510MywB5T2KdC8v/0oTlEoPcMsRM=
|
|
@ -1,27 +1,33 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"fmt"
|
||||
"github.com/dariubs/percent"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func wordCount(str string) map[string]int {
|
||||
wordList := strings.Fields(str)
|
||||
counts := make(map[string]int)
|
||||
for _, word := range wordList {
|
||||
_, ok := counts[word]
|
||||
if ok {
|
||||
counts[word] += 1
|
||||
} else {
|
||||
counts[word] = 1
|
||||
}
|
||||
}
|
||||
return counts
|
||||
var alphabet = []rune{
|
||||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
||||
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
|
||||
}
|
||||
|
||||
func letterCount(inputText string) {
|
||||
count := make([]int, len(alphabet))
|
||||
frequency := make([]float64, len(alphabet))
|
||||
totalCount := 0
|
||||
for index, letter := range alphabet {
|
||||
count[index] = strings.Count(inputText, string(letter))
|
||||
count[index] += strings.Count(inputText, string(letter+32))
|
||||
totalCount += count[index]
|
||||
}
|
||||
for index := range alphabet {
|
||||
frequency[index] = percent.PercentOf(count[index], totalCount)
|
||||
}
|
||||
for index, letter := range alphabet {
|
||||
fmt.Printf("The letter %c (%c) occurs %d times in the text and the frequency in percent is %0.2f\n", letter, letter+32, count[index], frequency[index])
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
strLine := "Australia Canada Germany Australia Japan Canada"
|
||||
for index,element := range wordCount(strLine){
|
||||
fmt.Println(index,"=>",element)
|
||||
}
|
||||
letterCount("This is a test to check for something.Zz")
|
||||
}
|
Reference in a new issue