python - 如何在 Scala 中获取子字符串集的字典?
问题描述
我有一个名为“wordAndPronounciation.txt”的文本文件,其中包含以下内容。预期的输出是作为键的单词和单词后面的任何字符串作为值连接在一起。
DEFINE D IH0 F AY1 N
PHOTOGRAPH F OW1 T AH0 G R AE2 F
输入:"wordAndPronounciation.txt"
输出:{"DEFINE": "DIH0FAY1N", "PHOTOGRAPH": "FOW1TAH0GRAE2F"}
在 Python 中,我可以做到这一点
def wordAndPronounciation(filename):
table = {}
with open(filename,'r') as x:
for i in x:
table[i.split(' ', 1)[0]] = ''.join(i.split()[1:])
return table
现在我如何在 Scala 中做到这一点?
我试过这个,但我认为它不正确。
for (line <- Source.fromFile(filename).getLines) {
first, *middle, last = text.split()
*middle = *middle.concat(last)
table=Map(first -> *middle) }
还有一件事,有没有一种简单的方法可以在 Scala 中反转字符串?在python中,我可以做到这一点,在哪里string = "CAT"
和你
print(string[::-1])
我尝试用这个来反转 Scala 中的字符串
var reversedC = ("" /: string)((a, x) => x + a)
,但它给出了参数错误。
解决方案
这是您的 Python 代码的粗略等价物。
def wordAndPronounciation(fileName: String): Map[String,String] =
io.Source.fromFile(fileName) //open file
.getLines() //read file line-by-line
.map(_.split("\\s+")) //spit on spaces
.map(a => (a.head, a.tail.reduce(_+_))) //create tuple
.toMap //as dictionary
附言"reverse".reverse //res0: String = esrever
推荐阅读
- php - PHP函数在应该返回多行时只返回一行
- vba - VBA word - 为表格设置字体样式
- node.js - 在再次刷新后保存mongoDB数据时保存相同的数据
- amazon-web-services - 如何将 www 重定向到 AWS 上的非 www 静态网站
- angular - 拖放列表内的项目以及对内部项目进行排序
- node.js - 如何在 pm2 中按日期分隔日志?
- javascript - 如何在 val: 'this text' ionic 5 Angular 中添加换行符?
- reactjs - 为什么样式不会从状态改变?
- xpath - 如何定义/定位这个 xpath
用这个身份证? - postgresql - AWS lambda PostgreSQL RDS 连接限制问题