首页 > 解决方案 > 如何在 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),但它给出了参数错误。

标签: pythonscala

解决方案


这是您的 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


推荐阅读