Vanguard
Vanguard

Reputation: 55

Scala File lines to Map

I'm Currently opening my files and utilizing .getLines to retrieve each lines from the file with a word and its phonetic pronunciation separated by two white spaces, i'm confused as to how would i go about Mapping the word and its pronunciation in Scala as i'm fairly new to the language. i've previously though to utilize split and separate the words and their sounds into different lines,but, i'm lost

Currently i Started with

  def words(filename: String, word: String): Unit = {
    val file = Source.fromFile(filename).getLines().drop(56)
    for(x <- file){
      
    }

 }

EX:

ARTI  AA1 R T IY2
AASE  AA1 S
ABAIR  AH0 B EH1 R
AB  AE1 B

Result:

Map("AARTI -> "AA1 R T IY2","AASE" -> "AA1 S", "ABAIR" -> " AH0 B EH1 R")

Upvotes: 0

Views: 1481

Answers (2)

Tim
Tim

Reputation: 27366

If your lines are in file then this will create a Map from the first word to the rest of the string:

val res: Map[String, String] = file.map(_.span(_.isLetter))(collection.breakOut)

The values in the Map will contain leading space characters so you may want to call trim on them before using them.

  1. The map call processes each line in turn.

  2. The span method splits the line into a tuple where the first value is your word and the second is the rest of the line.

  3. Using collection.breakOut tells map to put the results directly into a Map rather than going through an intermediate array or list.

Upvotes: 1

prayagupadhyay
prayagupadhyay

Reputation: 31232

  • iterate each line
  • split by 2 white spaces " "
  • create a tuple of (a -> b)
  • convert Array[Tuple[A, B]] => Map[A, B]

example,

    val data =
      """
ARTI  AA1 R T IY2
AASE  AA1 S
ABAIR  AH0 B EH1 R
AB  AE1 B
      """.stripMargin

    val lines: Array[String] = data.split("\n").filter(_.trim.nonEmpty)
    // if you are reading from file
    // val lines = Source.fromFile("src/test/resources/my_filename.txt").getLines()

    val res: Array[Tuple2[String, String]] = lines.map { line =>
      line.split("  ") match { case Array(a, b) => a -> b }
    }

    println(res.toMap)

output:

Map(ARTI -> AA1 R T IY2, AASE -> AA1 S, ABAIR -> AH0 B EH1 R, AB -> AE1 B)

Running example - https://scastie.scala-lang.org/prayagupd/jBCnEhUPQJCMPKP9TXlgWA

How to read entire file in Scala?

Upvotes: 2

Related Questions