2

How can I count the number of strings that occurs exactly once in a text file using GO? I have read some of the package description of golang, maybe I should use bufio.NewScanner to read the contents of the passed-in file a line at a time. Then I try to use map to count the occurrence of each string:

stringcount := make(map[string]int)

how can I update the data of this empty map? For example, if the first string is "hello" in the file, how to make stringcount["hello"] = 1?

Here is my try:

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {

    frequencyofWord := map[string]int{}

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }

    s := strings.Fields(scanner.Text()) //one more question : is strings.Fields used correctly here?
    countSingleton(s)

}

func countSingleton(a []string) {
    //here how to update the map according to the text read ?//
}
5
  • Please update your post to reflect the actual question you're asking. Are you asking what the difference between Scanner and Reader is? Are you asking how to find the unique strings in a list? Are you asking how to read the lines from a file? Don't ask all three at once. I suspect each of these are already answered elsewhere, but some clarity will help us point you where you need to go. Jan 27, 2014 at 5:13
  • thanks for the reply,I will try to make it clear. The main question is how to find the unique string in a text file and output how many unique strings are there in this file.
    – MicM
    Jan 27, 2014 at 5:24
  • It sounds like you're asking about maps. Have you gone through the tutorial? tour.golang.org Jan 27, 2014 at 5:44
  • @KyleLemons Yes I did, but the tour only gives example that assigns fixed values to a map. I wonder how to do it when takes a file as input. I update my question again, giving what I have tried to do.
    – MicM
    Jan 27, 2014 at 7:51
  • @user3221327 Are you sure you mean string? Because checking each substring of a text file against each other substring is pretty damn expensive.
    – Cubic
    Jan 27, 2014 at 8:27

1 Answer 1

2

Use bufio.NewScanner to break apart the lines, use strings.Fields to get the words, and use yourMap[theWord]++ to count the words.

Example: http://play.golang.org/p/3H6gfBlQL5

To get the list of the unique words, iterate over the map keys and append them to a slice, and then sort them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.