Find most used rune in txt.file


(Markus Sveggen) #1

I am new to Go, and I am currently working on a project where I have to create a program which does the following:

  • Count the number of lines with text in a txt. file.
  • Count the five most used runes in the same txt. file.
  • Write the result to a new txt. file.

I am new to Go, and unsure how to grasp these tasks. Does anyone have any tips on how I could do so? Most preferably with some lines of code to demonstrate.


(Yamil Bracho) #2

Start searching how to open a text file. Then, you can choose which approach it is appropiate for your case. I mean read the file line by line or read all lines in a string or an slice.


(Eric Lindblad) #3

What does ‘go run Bergen.go’ tell you?

% cat Bergen.go
package main

import "fmt"

    func reisebyraa() {
    s := "Besøk Bergen"

    fmt.Printf("%s, type: %T, len: %d\n", s, s, len(s))
    fmt.Printf("s[%d]: %v, type: %T\n", 0, s[0], s[0])
    li := len(s) - 1 // last index,
    fmt.Printf("s[%d]: %v, type: %T\n\n", li, s[li], s[li])

    rs := []rune(s)
    fmt.Printf("%v, type: %T, len: %d\n", rs, rs, len(rs))
}

func main() {
    reisebyraa()
}
%

Bergen.go being a utf-8 encoded file.

Try modifing the string to read “Visit Bergen” and run again.

Flagrantly adapted from an SO question.

R.P. wrote a bit here on a blog.


(Eric Lindblad) #4

Package ioutil


(Che) #5

Hello, I think by using a map data type could make implementation easier but with loss of speed

func main() {

	f, err := os.Open(TXTFILE)

	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return
	}

	defer f.Close()

	reader := bufio.NewReader(f)

	rc := 0
	for {
		s, err := reader.ReadString('\n')
		rc++
		if err == io.EOF {
			break
		}
		fmt.Print(graspRune(s))
	}
}

func graspRune(input string) map[rune]int {

    runes := make(map[rune]int)

    for _, val := range input {
        runes[val]++
    }

    return runes
}

(Eric Lindblad) #6

You might read this file.

https://golang.org/src/bufio/scan.go


(Markus Sveggen) #7

Thank you all. I will read the articles! The map solution sounds like my best plan as per now


(Eric Lindblad) #8

not specific to your question

mentioned in a blog Post a regex issue

apparently the idea originated in Plan 9

isalpharune(2)
rune(2)
runestrcat(2)