Scala新手求助:如何将文本每个单词转为单个Map对象
如何为字符串中的每个单词生成独立的单键值Map
你现在写的代码是把所有单词合并成了一个大Map,而且因为默认Map是无序的,输出顺序和文本里的单词顺序对不上。而你要的是给每个单词单独创建一个只包含该单词和数字1的小Map,最终得到一组Map集合。
解决办法
修改代码,直接把每个单词转换成Map[String, Int],而不是先生成元组再合并成大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. """ // 分割字符串得到单词数组,每个单词生成独立的Map val mappings = text.split("\\W+").map(word => Map(word -> 1)) // 取前5个打印 mappings.take(5).foreach(println)
运行结果
执行后会得到你想要的输出:
Map(It -> 1) Map(is -> 1) Map(a -> 1) Map(period -> 1) Map(of -> 1)
原代码问题说明
text.split("\\W+").map(_ -> 1)生成的是元组数组Array[(String, Int)],不是Map数组。- 调用
toMap会把所有元组合并成单个Map,重复的单词会被覆盖(Scala的toMap保留最后一次出现的键值对),而且默认Map是无序的,所以打印顺序和文本里的单词顺序不一致。 - 元组的打印格式是
(key, value),和你期望的Map(key -> value)格式不符。
这段代码会保留文本中单词的出现顺序,因为split返回的数组是按文本顺序排列的,map后的Map数组也会维持这个顺序。
内容的提问来源于stack exchange,提问作者Aaricia
相关产品推荐
相关产品推荐

