我需要在我的代码中将电视收视率(针对电视节目)转换为该收视率的案例对象。因此我有一个这样的案例匹配:
def fromString(s: String): Option[TvRating] = s.toLowerCase match {
case "tvy" | "tv-y" | "tv y" | "y" => Some(tvY)
case "tvg" | "tv-g" | "tv g" | "g" => Some(tvG)
case "tvpg" | "tv-pg" | "tv pg" | "pg" => Some(tvG)
case "tv14" | "tv-14" | "tv 14" | "14" => Some(tv14)
case "tvma" | "tv-ma" | "tv ma" | "ma" => Some(tvMA)
case _ => Some(noTvRating)
}
如您所见,我正在尝试匹配每个评级的所有排列,这很麻烦,而且仍然没有考虑到“tv.14”或“成熟观众”等内容。
是否有像 soundX 这样的算法,但对于像这些评级这样的代码,我可以将其用作最后的手段。然后我的代码将如下所示:
def fromString(s: String): Option[TvRating] = s.toLowerCase match {
case "tvy" | "tv-y" | fancyAlgo(s, "tv-y") => Some(tvY)
case "tvg" | "tv-g" | fancyAlgo(s, "tv-g") => Some(tvG)
case "tvpg" | "tv-pg" | fancyAlgo(s, "tv-pg") => Some(tvG)
case "tv14" | "tv-14" | fancyAlgo(s, "tv-14") => Some(tv14)
case "tvma" | "tv-ma" | fancyAlgo(s, "tv-ma") => Some(tvMA)
case _ => Some(noTvRating)
}
或者我可以使这些匹配更可靠的任何其他建议。由于 tv-g 不是像“狗”或“马”这样的词,我不能根据音频或类似的发音词来判断。
这是评级的一个例子。还有其他比赛。这是另一个星级评级示例(如烂番茄的电影评级)
def fromString(s: String): Option[StarRating] = s.toLowerCase match {
case "1" | "one star" | "one stars" => Some(oneStar)
case "1.5" | "1.5 stars" | "one and a half stars" => Some(oneAndHalfStar)
case "2" | "2 stars" | "two stars" => Some(twoStars)
case "2.5" | "2.5 stars" | "two and a half stars" => Some(twoAndHalfStars)
case "3" | "3 stars" | "three stars" => Some(threeStars)
case "3.5" | "3.5 stars" | "three and a half stars" => Some(threeAndHalfStars)
case "4" | "4 stars" | "four stars" => Some(fourStars)
case _ => Some(noStars)
}
干杯!
最佳答案
数据驱动:
val ratings = scala.collection.mutable.Map[String, String]() withDefaultValue "noTVRating"
type TvRating = String
def addRatingStyle(base:String, result:String) = {
val suffix = base.stripPrefix("tv")
ratings += ("tv"+suffix->result)
ratings += ("tv-"+suffix->result)
ratings += ("tv "+suffix->result)
ratings += (suffix->result)
}
addRatingStyle("tvy", "tvy")
addRatingStyle("tvg", "tvg")
addRatingStyle("tvpg", "tvpg")
addRatingStyle("tv14", "tv14")
addRatingStyle("tvma", "tvma")
def fromString(s: String): Option[TvRating] = Some(ratings(s.toLowerCase))
关于algorithm - 基于算法的大小写匹配字符串。我应该使用哪种算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42399109/