Как сгенерировать n-грамм в скале? - PullRequest
7 голосов
/ 24 ноября 2011

Я пытаюсь закодировать диссоциированный алгоритм печати на основе n-граммы в scala.Как создать n-грамм для больших файлов: например, для файла, содержащего «пчела - пчела пчел».

  1. Сначала нужно выбрать случайный n-грамм.Например, пчела.
  2. Затем она должна искать n-граммы, начиная с (n-1) слов.Например, пчела.
  3. печатает последнее слово этой н-граммы.Потом повторяется.

Не могли бы вы дать мне несколько советов, как это сделать?Приносим извинения за неудобства.

Ответы [ 3 ]

13 голосов
/ 24 ноября 2011

Ваши вопросы могут быть немного более конкретными, но вот моя попытка.

val words = "the bee is the bee of the bees"
words.split(' ').sliding(2).foreach( p => println(p.mkString))
4 голосов
/ 24 мая 2013

Вы можете попробовать это с параметром n

val words = "the bee is the bee of the bees"
val w = words.split(" ")

val n = 4
val ngrams = (for( i <- 1 to n) yield w.sliding(i).map(p => p.toList)).flatMap(x => x)
ngrams foreach println

List(the)
List(bee)
List(is)
List(the)
List(bee)
List(of)
List(the)
List(bees)
List(the, bee)
List(bee, is)
List(is, the)
List(the, bee)
List(bee, of)
List(of, the)
List(the, bees)
List(the, bee, is)
List(bee, is, the)
List(is, the, bee)
List(the, bee, of)
List(bee, of, the)
List(of, the, bees)
List(the, bee, is, the)
List(bee, is, the, bee)
List(is, the, bee, of)
List(the, bee, of, the)
List(bee, of, the, bees)
3 голосов
/ 17 декабря 2013

Вот потоковый подход.Это не потребует слишком много памяти при вычислении n-грамм.

object ngramstream extends App {

  def process(st: Stream[Array[String]])(f: Array[String] => Unit): Stream[Array[String]] = st match {
    case x #:: xs => {
      f(x)
      process(xs)(f)
    }
    case _ => Stream[Array[String]]()
  }

  def ngrams(n: Int, words: Array[String]) = {
    // exclude 1-grams
    (2 to n).map { i => words.sliding(i).toStream }
      .foldLeft(Stream[Array[String]]()) {
        (a, b) => a #::: b
      }
  }

  val words = "the bee is the bee of the bees"
  val n = 4
  val ngrams2 = ngrams(n, words.split(" "))

  process(ngrams2) { x =>
    println(x.toList)
  }

}

ВЫХОД:

List(the, bee)
List(bee, is)
List(is, the)
List(the, bee)
List(bee, of)
List(of, the)
List(the, bees)
List(the, bee, is)
List(bee, is, the)
List(is, the, bee)
List(the, bee, of)
List(bee, of, the)
List(of, the, bees)
List(the, bee, is, the)
List(bee, is, the, bee)
List(is, the, bee, of)
List(the, bee, of, the)
List(bee, of, the, bees)
...