nlp - 斯坦福 corenlp : top K ngrams with count

标签 nlp stanford-nlp n-gram

如何使用 stanford corenlp 获取前 K 个 ngram 及其计数?我知道我可以使用 HashMap 或 Trai 编写此代码,但我的语料库非常大(每篇文章有 20 万篇文章,平均大小为 30KB),而且我想要 5gram,因此内存需求将很大。因此我想知道是否可以使用 corenlp 来达到此目的。 因此,给定一个语料库,它应该仅返回以下格式的前 K 个 ngram:

word1 word2 word3 word4 word5:频率

我不需要任何概率模型。

最佳答案

CoreNLP 没有任何东西可以帮助您有效地存储 ngram。它在这里能帮助您的就是对文本进行标记(如果您关心的话,还可能将文本分割成句子)。

如果您的语料库足够大,以至于您不能仅使用哈希表来保留 n 元语法计数,则必须使用替代的、更节省空间的表示形式(例如前缀 trie)。

例如,我刚刚在 Clojure 中做了一个快速测试,我计算了古腾堡国王詹姆斯五世圣经中的 5 克。使用 HashMap 存储 752K 不同 5-gram 的计数使用了 248 MB 堆。使用前缀 trie 来存储计数使用了 57 MB——减少了 77%。

作为引用,这里是使用前缀 attempts 的完整 Clojure 程序:

(ns nlp.core
  (:require [clojure.string :as string]))

(defn tokenize
  "Very simplistic tokenizer."
  [text]
  (string/split text #"[\s\:_\-\.\!\,\;]+"))

(defn get-bible-kjv-tokens []
  (tokenize (slurp "/Users/wiseman/nltk_data/corpora/gutenberg/bible-kjv.txt")))

(defn ngrams [n tokens]
  (partition n 1 tokens))

(defn build-ngram-trie [n tokens]
  (->> tokens
       (ngrams n)
       (reduce (fn [trie ngram]
                 (update-in trie ngram #(if % (inc %) 1)))
               {})))

(defn enumerate-trie [trie]
  (if (not (map? trie))
    (list (list trie))
    (apply concat
           (for [[k v] trie]
             (map #(cons k %)
                  (enumerate-trie v))))))

(defn print-trie [trie]
  (doseq [path (enumerate-trie trie)]
    (println (string/join " " (butlast path)) ":" (last path))))


(defn -main []
  (let [ngram-counts (->> (get-bible-kjv-tokens)
                          (build-ngram-trie 5))]
    (print-trie ngram-counts)))

国王詹姆斯五世圣经的输出:

$ lein run -m nlp.core | sort -r -k7,7 -n ngrams.txt  | head
And it came to pass : 383
the house of the LORD : 233
the word of the LORD : 219
of the children of Israel : 162
it came to pass when : 142
the tabernacle of the congregation : 131
saith the LORD of hosts : 123
it shall come to pass : 119
And the LORD said unto : 114
And the LORD spake unto : 107

有关获得更高效率的一些建议,以下论文讨论了大型语料库的高效 n 元语法存储:

ADtrees for Sequential Data and N-gram Counting - 使用自定义数据结构。

Faster and Smaller N-Gram Language Models - “我们最紧凑的表示可以以每个 n-gram 23 位的形式存储所有 40 亿个 n-gram 以及 Google n-gram 语料库的相关计数,这是迄今为止最紧凑的无损表示”

关于nlp - 斯坦福 corenlp : top K ngrams with count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564296/

相关文章:

python - 了解 TfidfVectorizer 输出

c# - 在不同文档中查找相似段落

nlp - 他们有使用二元概率进行句子解析的算法吗?

python - 如何在 python nltk 中获取 n-gram 搭配和关联?

nlp - 如何在未标记的数据上微调 BERT?

python - Jython:导入错误:没有名为 multiarray 的模块

java - Stanford CoreNLP python接口(interface)安装错误

nlp - 斯坦福大学 NER prop 文件中 DistSim 的含义

Python 计数元组在列表中的出现次数

r - 在 R 中使用 text2vec 预测下一个单词