我正在尝试使我的Scala代码像我的伪代码一样。我可以轻松地将伪代码转换为 Python 代码并获得所需的值。但是,我的 Scala 代码给出了各种错误。如何让我的 Scala 代码与伪代码执行相同的方式?
伪代码:
#def word(file, first_word, second_word):
# -open file and read the file
# -create a hash table called table_1
# -create a hash table called table_2
# -create a hash table called table_3
# -create a empty string called string_1
# -create a empty string called string_2
# -loop through file line by line
# -take every first word of each line as key and concatenate the
# pronunciations of each line as value and store this in
# table_1
# -loop through the keys and values in table_1
# -loop through the values of table_1 and add only the values
# to string_1 that are not numeric values; this new string
# will now be the value of table_2 with the key still remaining
# as the word
# -loop through the keys and values in table_2
# -now take the string values of table_2 and reverse that
# backwards
# -loop through the reversed string and keep adding the
# values to string_2 until you encounter a vowel.
# -now you add this new string to table_3 as values with
# the same words as before as keys
# -if first_word is not in table_3 or second_word is not in
# table_3, then return an empty list
# -if the values of first_word and the values of second_word
# are equal; then return True, meaning that the words rhyme
# -if the values of first_word and the values of second_word
# are not equal; then return False, meaning that the words
# don't rhyme
这是伪代码的 scala 版本。它与伪代码不完全匹配,但也许它提供了一些有用的提示
val source = Source.fromFile(filename).getLines
// take every first word of each line as key and concatenate the
// pronunciations of each line as value and store this in table_1
val table1: Map[String, String] = source.map { line =>
val words = line.split(" ")
(words.head, words.drop(1).mkString)
}
.toMap
// loop through the values of table_1 and add only the values
// to string_1 that are not numeric values; this new string
// will now be the value of table_2 with the key still remaining
// as the word
val table2 = table1.map { case (key, value) =>
val string_1 = value.toCharArray
.filter(!_.isDigit)
.mkString
(key, string_1)
}
.toMap
// -loop through the reversed string and keep adding the
// values to string_2 until you encounter a vowel.
// -now you add this new string to table_3 as values with
//the same words as before as keys
val table3 = table2.map { case (key, value) =>
val string_2 = value
.reverse
.takeWhile("AEIOU".indexOf(_) == -1)
(key, string_2 + value.charAt(value.length - 1 - string_2.length))
}
.toMap
val first_word = "CAT"
val second_word = "xx"
if (table3.get(first_word).isDefined && table3.get(second_word).isDefined) {
Left(table3.get(first_word).get == table3.get(second_word).get)
} else {
Right(List())
}