【问题标题】:How to count the appearance of each word in text如何计算文本中每个单词的出现次数
【发布时间】:2018-07-24 19:56:08
【问题描述】:

或者问题也可能是: Go 获取词袋的方法是什么?

例如,如果输入是

"This is a big apple tree. I love big big apple! 42"

那么我如何获得每个单词计数的 map 输出(并且,如果方便的话,沿途进行一些简单的字符串解析,例如只保留字母并降低它们):

{this=1, is=1, a=1, big=3, apple=2, tree=1, i=1, love=1}


一些 Kotlin 代码的简单版本可以是:

fun main(args: Array<String>) {
    val inputText = "This is a big apple tree. I love big big apple! 42"

    val map = inputText.replace("[^a-zA-Z]+".toRegex(), " ") // only keep letters
            .trim()
            .toLowerCase()
            .split(" ")
            .groupingBy { it }
            .eachCount()

    println(map)
}

输出{this=1, is=1, a=1, big=3, apple=2, tree=1, i=1, love=1}

我想知道用 Golang 做这种事情的等效方法是什么。 希望它既快速又易于阅读。

【问题讨论】:

  • Go 的方式是显而易见的方式:play.golang.org/p/XPTJ5q_-mSv
  • @Peter 谢谢 Peter,我是 Go 新手,听说 Go 很容易阅读。只是想更好地体验 Go 做这些事情,因为我正在考虑将一些项目从 Java 迁移到 Go。 BTW 是否可以在 Go 中进行正则表达式操作?
  • 你应该去参观一下,感受一下 Go:tour.golang.org

标签: go nlp


【解决方案1】:

例如,

package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "This is a big apple tree. I love big big apple! 42"
    fields := strings.FieldsFunc(text, func(r rune) bool {
        return !('a' <= r && r <= 'z' || 'A' <= r && r <= 'Z')
    })
    words := make(map[string]int)
    for _, field := range fields {
        words[strings.ToLower(field)]++
    }
    fmt.Println(words)
}

游乐场:https://play.golang.org/p/6J-ptfCoJ8r

输出:

map[tree:1 i:1 love:1 this:1 is:1 a:1 big:3 apple:2]

【讨论】:

  • 非常感谢。您不需要初始化 map 中的所有零,这非常酷。顺便说一句,你知道让这段代码在多核 CPU 上运行是否简单?假设文本是超长的,还是很长的列表中的文本太多?我知道在 java 中,也许可以使用 parallelstream 和一些 lambdas 来实现这一点。如何在 go 中执行此操作,是否容易?如果不是太难,那么我正在考虑在 Go 中从 java/kotlin 迁移一个项目。
猜你喜欢
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多