2017-04-15 39 views
0

我有一个巨大的文本文件。我希望从该文本文件中出现短语“我感觉”后出现的单词数量。计算文本文件中的模式

这里是什么样的文件就像一个小例子:

i feel awesome 
i feel nothing but i also feel awesome 
i feel good. 

,我读了包含文本文件和匹配行“我觉得”。现在我的输出形式是:

res3: Array[String] = Array("awesome", "nothing", "good", ....) 

我需要在文本文件中找到这些词的出现。我使用至今为此,

代码如下:

val c1 = scala.io.Source.fromFile("text.txt", "UTF-8"). 
    getLines.flatMap(regexpr.findAllIn(_).toList). 
    foldLeft(Map.empty[String, Int]) { 
    (count, word) => count + (word -> (count.getOrElse(word, 0) + 1)) 
    } 

但是,这给我的只有几句话是存在该数组中的计数。 例如,它返回:

c1: scala.collection.immutable.Map[String,Int] = Map(awesome -> 1, nothing -> 4) 

不退还的出现在列表中的所有字计数。另外,如何将Map[String,Int]写入文本文件?

+1

可能的复制[斯卡拉初学者 - 在文件来算的话最简单的方法(http://stackoverflow.com/questions/15487413/scala-beginners-simplest-way-to- count-words-in-file) – starlight

+0

您所指的解决方案不会返回所有匹配项。我已更新原始评论 – AzkaGilani

回答

1

这里是行的在文本文件中的列表:

val lines = scala.io.Source.fromFile("text.txt","UTF-8").getLines 

这里是一个Java打印作家:

val f = new java.io.PrintWriter(new java.io.File("counts.txt")) 

这里后,分组的话比赛“感觉”语句写入文本文件:

lines.flatMap { 
    "i feel (\\w+)".r.findAllMatchIn(_).map(_.group(1)) // Return only paren matches 
}.toTraversable.groupBy(identity).mapValues(_.size).foreach { 
    case (word, count) => f.write(s"$count\t$word\n") // Separate by tab 
} 

然后关闭文件

f.close() 

见的Scala documentation on regular expressions

+0

中的代码,请检查我更新的问题。你错过了这一点。我需要在大文本文件中找到特定数组中存在的字符串。 – AzkaGilani

+0

谢谢这么多:) – AzkaGilani