Linda Su
Linda Su

Reputation: 455

How to read a file and store words to a list in scala?

I'm trying to store all the words present in a txt file, except punctuations and digits, to a list?

I'm very new to scala and can't figure out how to do it? Can anybody help?

EDIT:

I'm doing it this way right now:

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

      }
      println(lst)

It's giving me a redline on lst=line and says reassignment to a val. I don't know why :(

Upvotes: 2

Views: 3508

Answers (2)

Eugene Zhulenev
Eugene Zhulenev

Reputation: 9734

You can use scala.io.Source with filter by regex and toList at the end

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

Update:

What's inside your file? This simple code works as expected

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

  println(list)

Output:

List(aaa, bbb, AZvb)

Upvotes: 1

Gennadiy
Gennadiy

Reputation: 326

Assuming that each line can have multiple words a better solution would be

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

Upvotes: 4

Related Questions