如何在scala中读取文件并将单词存储到列表中?

如何在scala中读取文件并将单词存储到列表中?,scala,Scala,我正在尝试将txt文件中存在的所有单词(除了标点符号和数字)存储到列表中 我是scala的新手,不知道怎么做?有人能帮忙吗 编辑: 我现在就这样做: for(line <- Source.fromFile("src/stop_words.txt").getLines()) { //println(line) lst = line } println(lst) for(line您可以使用scala.io.Source,并在末尾使

我正在尝试将txt文件中存在的所有单词(除了标点符号和数字)存储到列表中

我是scala的新手,不知道怎么做?有人能帮忙吗

编辑:

我现在就这样做:

for(line <- Source.fromFile("src/stop_words.txt").getLines())
      {
      //println(line)
      lst = line

      }
      println(lst)

for(line您可以使用scala.io.Source,并在末尾使用regex和toList过滤

io.Source.fromFile("path/to/file.txt").
  getLines().
  filter(_.matches("[A-Za-z]+")).
  toList
更新

你的文件里有什么?这个简单的代码可以正常工作

val list = io.Source.fromBytes(
    """aaa
      |bbb
      |123
      |.-ddg
      |AZvb
    """.stripMargin.toArray.map(_.toByte)).
    getLines().
    filter(_.matches("[A-Za-z]+")).
    toList

  println(list)
输出:

List(aaa, bbb, AZvb)

假设每行可以有多个单词,则更好的解决方案是

val words = """([A-Za-z])+""".r
val all = io.Source.fromFile("path/to/file.txt").getLines.flatMap(words.findAllIn).toList

看一看
scala.io.Source.fromFile(…)
。然后过滤内容中的标点和数字。@Brian你能看到我问题中的编辑吗。我有一些问题。嗨,当我执行var fillist=io.Source.fromFile(“/Users/xyz/Desktop/file1.txt”).getLines().filter(u.matches(“[a-Za-z]+”)).toList println(fillist)我得到一个空列表作为输出,这是为什么?请看我的更新,很难说没有文件的内容,它应该可以工作,或者需要更新正则表达式以匹配