You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

原代码问题说明

  1. text.split("\\W+").map(_ -> 1)生成的是元组数组Array[(String, Int)],不是Map数组。
  2. 调用toMap会把所有元组合并成单个Map,重复的单词会被覆盖(Scala的toMap保留最后一次出现的键值对),而且默认Map是无序的,所以打印顺序和文本里的单词顺序不一致。
  3. 元组的打印格式是(key, value),和你期望的Map(key -> value)格式不符。

这段代码会保留文本中单词的出现顺序,因为split返回的数组是按文本顺序排列的,map后的Map数组也会维持这个顺序。

内容的提问来源于stack exchange,提问作者Aaricia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:15:32