【问题标题】:How to store words in each line of a file to a list scala如何将文件每一行中的单词存储到列表scala
【发布时间】:2015-02-01 21:34:46
【问题描述】:

我正在尝试逐行读取文件并将每行中的所有单词存储到一个列表中,然后对其执行一些计算。

我正在做以下事情:

for(line <- Source.fromFile("file1.txt").getLines())
 {
   var words_in_line = line.split("\\s+")
   println(words_in_line)
}

但是,这会打印出类似的内容:

[Ljava.lang.String;@3535a92b
[Ljava.lang.String;@55f56157

这是什么?为什么不在列表的每一行中打印单词?

编辑:

我现在正在这样做:

val w2 = """([A-Za-z])+""".r
 for(line <- Source.fromFile("/Users/Martha/Desktop/file1.txt").getLines.flatMap(w2.findAllIn))
 {
   println("this is")
   println(line)

   var w1 = line.split("\\s+")
   //var w2 = w1.deep.mkString(" ")
   var w3 = line.split("\\s").toList
   println(w3)

 }

只得到单词,没有数字或标点符号。但是,它只给了我列表中的单个单词作为输出,而不是行中的单词列表。为什么会这样?

【问题讨论】:

    标签: scala collections scala-collections


    【解决方案1】:
    var words_in_line = line.split("\\s+")
    
    //words_in_line is an Array
    

    你不能通过println(words_in_line)打印Array

    试试

    scala> var line="hey hello this is demo"
    line: String = hey hello this is demo
    
    scala> var words=line.split("\\s+")
    words: Array[String] = Array(hey, hello, this, is, demo)
    
    scala> words map println
    hey
    hello
    this
    is
    demo
    res8: Array[Unit] = Array((), (), (), (), ())
    

    你想要List(hey, hello, this, is, demo) 就像那时

    scala> var words=line.split("\\s+").toList
    words: List[String] = List(hey, hello, this, is, demo)
    
    scala> println(words)
    List(hey, hello, this, is, demo)
    

    【讨论】:

    • 但是,这不是以单词列表的形式打印出来的!第一个将其简单地打印为单词,第二个将其制成一个字符串。我想将其打印为 List(abc, vdc,...)
    • 非常感谢!你能再帮我一件事吗?您能否在问题中阅读我的编辑。我遇到了麻烦。 :(
    【解决方案2】:

    当您执行 getLines 和 flatMap 时,结果是单个单词的列表。如果您需要行中的单词列表,则需要将这两个调用分开:

    for( line  <- io.Source.fromFile("all.txt").getLines ) {
       val words = w2.findAllIn(line)
       println("this is")
       println(words.mkString(" "))
     }
    

    【讨论】:

      【解决方案3】:
      var w3 = line.split("\\s")
      w3.foreach(m -> println(m))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 1970-01-01
        • 2019-05-23
        • 2014-06-21
        • 1970-01-01
        • 2015-08-21
        相关资源
        最近更新 更多