how do i print out the 5 most common runes and count them, from a text file?
You can go through the file rune by rune, maybe after reading it using
ioutil.ReadFile and converting to
string, keeping track of how many you see of each. A
map[rune]int is useful here. Then copy the keys into a slice of runes (
rune, you’ll need to iterate over the map to do this), sort it by the frequency in the map (the
sort.Slice function is nice here), and print the five first (or last, depending on the sort) items.
(This sounds like homework so I’m giving you useful hints and pointers instead of the answer.)
Hi I’m trying to do the same thing, but I don’t understand why i should convert to string if the hashmap is gonna be of rune?
I am really new to Go so could you explain this in a easier way?
When you iterate over a string, you get runes. When you iterate over a byte slice you get bytes. Reading a file typically gets you a byte slice, which you then convert to a string to iterate over:
someStr = String(someByteSlice).
Iterating over a string like this is nice because runes are unicode code points, like 國 which is one code point but multiple bytes. You probably don’t want to count the occurrence of the individual bytes that make up the rune.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.