Home > OS >  How to divide each word of a text into several different maps?
How to divide each word of a text into several different maps?

Time:12-18

I am a beginner in scala and I am looking to create a value mapping that associates to each word of the string "text" the number 1 in the form of a Map.

val text = """It is a period of civil wars in the galaxy. A brave alliance of underground freedom fighters has challenged the tyranny and oppression of the awesome GALACTIC EMPIRE.
Striking from a fortress hidden amoug the billion stars of the galaxy, rebel spaceships have won their first victory in a battle with the powerful Imperial Starfleet.
The EMPIRE fears that another defeat could bring a thousand more solar systems into the rebellion, and Imperial control over the galaxy would be lost forever.
To crush the rebellion once and for all, the EMPIRE is constructing a sinister new battle station. Powerful enough to destroy an entire planet, its completion spells certain doom for the champions of freedom.
"""

I tried this but it is not the result I am looking for:

val mapping = text.split("\\W ").map(_ -> 1).toMap

mapping.take(5).foreach(println)

//(sinister,1)
//(fighters,1)
//(battle,1)
//(galaxy,,1)
//(tyranny,1)

What I would like to get out is this:

val mapping = ...

mapping.take(5).foreach(println)
// Map(It -> 1)
// Map(is -> 1)
// Map(a -> 1)
// Map(period -> 1)
// Map(of -> 1)

How could I have a release like this?

Thanking you in advance for the help you will give me!

CodePudding user response:

split uses a regular expression as a separator. You can use \\W , which means "one or more non-word characters" (spaces, new lines, punctuation etc.).

text.split("\\W ").map(_ -> 1).toMap

CodePudding user response:

Finally the right answer was this:

val mapping = text.split("\\W ").map(word => Map(word -> 1))

Thank you for helping me!

  • Related