0

我有一个句子的二元组列表和另一个相关二元组的原始列表,我想检查句子中是否存在任何相关二元组,然后我想返回句子。我正在考虑按如下方式实现它:将列表中的每个二元组映射到它们来自的句子,然后对键进行搜索并返回值。

例子:

relevantbigrams = (This is, is not, not what)
bigrams List(list(This of, of no, no the),list(not what, what is))

所以每个列表都是一个单独的句子的二元组。这里第二句中的“不是什么”匹配,所以我想返回第二句。我计划制作一张地图(“This of”->“This of no the”、“of no”->“This of no the”、“not what”->“not what is”)。等并返回在相关二元组上匹配的句子,所以在这里我返回“不是什么”

这是我的代码:

val bigram = usableTweets.map(x =>Tokenize(x).sliding(2).flatMap{case Vector(x,y) => List(x+" "+y)}.map(z => z, x))
for(i<- 0 to relevantbigram.length)
    if(bigram.contains(relevantbigram(i)))) bigram.get(relevantbigram(i))
    else useableTweets.head
4

1 回答 1

1

你得到了订单或flatMap错误map的方式:

val bigramMap = usableTweets.flatMap { x => 
    x.split(" ").sliding(2).
      map(bg => bg.mkString(" ") -> x)
} toMap

然后你可以像这样进行搜索:

relevantbigrams collect { rb if theMap contains rb => bigramMap(rb) }

或者

val found = 
  for { 
    rb <- relevantbigrams
    sentence <- theMap get rb
  } yield sentence

两者都应该给你一个列表,但是从你的代码看来,如果你的搜索什么也没找到,你希望默认为第一句:

found.headOption.getOrElse(usableTweets.head)
于 2013-03-08T00:37:51.347 回答