簡體   English   中英

使用Scala中的get行從文件讀取時忽略空格

[英]Ignore spaces when reading from a file using get lines in Scala

我正在嘗試從文件中讀取輸入並使用映射對它們進行計數。我想從文件中讀取時忽略空格。

val lines = Source.fromFile("file path","utf-8").getLines()

val counts = new collection.mutable.HashMap[String, Int].withDefaultValue(0)
lines.flatMap(line => line.split(" ")).foreach(word => counts(word) += 1)
for ((key, value) <- counts) println (key + "-->" + value)

當我嘗試將此代碼用於以下輸入時。

hello hello
    world goodbye hello
  world

輸出是

world-->2
goodbye-->1
hello-->3
-->2

它計數2個空格。 我該如何解決?

lines.flatMap(_.trim.split("\\s+"))

可能的一種方法是使用過濾器:

lines
  .flatMap(line => line.split(" "))
  .filter(_ != " ")
  .foreach(word => counts(word) += 1)

無論如何,我會說有更好的方法,您可以強制迭代器使用toList方法進行評估,然后將groupBycollect groupBy使用:

Iterator("some  word", "some    other")
  .flatMap(_.split(" "))
  .toList
  .groupBy(identity)
  .collect { case (a,b) if !a.isEmpty => (a, b.length)}

輸出:

Map(some -> 2, word -> 1, other -> 1)

還要注意,這種方法最有可能比您使用的方法效率低,因為它創建了許多中間集合,我還沒有對其進行任何基准測試,對於大文件,它可能不是最佳選擇。

這種方法會從每行以"\\\\W+"提取單詞,而不管單詞之間的空格數量如何,

Source.fromFile("filepath")
  .getLines
  .flatMap(_.trim.split("\\W+"))
  .toArray.groupBy(identity)
  .map ( kv => kv._1 -> kv._2.size )

因此

res: Map(world -> 2, goodbye -> 1, hello -> 3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM