java - scala计算读取文件中包含的列表中的字符串
问题描述
我是 SO 新手,但花了几天时间研究与问题相关的问题。我发现的最接近的相关问题是如何将文件中一行的每个单词与 scala 中的列表元素进行比较?但这可以追溯到 2014 年,所以认为现在可能有不同的解决方案。
同样在上面引用的帖子中,最佳答案使用了我试图避免的可变数据结构。Dima 的最后一个答案看起来更实用,但没有奏效:(
我正在尝试在 SCALA 中创建一个类似的程序,除了输出还应该包含关键字的总计数并且应该输出所有关键字,即使没有找到匹配项,因此计数为零。
要检查的关键字被硬编码到列表中,但是我还想添加包含关键字的第二个用户提供的参数的选项。到目前为止,我已经达到以下但很糟糕:
object FileAnalyser extends App {
val hardcodedkeywords = List("foo", "bar", "hello")
if (args.length > 1) {
val keywords = args(1).toList
try {
val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
case(line, index) => line.split("\\W+").map { (_, index+1) }
} //.filter(keywords.contains(_)).groupBy { _._1 }.mapValues(_._2)
} catch {
case ioe: IOException => println(ioe)
case fnf: FileNotFoundException => println(fnf)
case _: Throwable => println("Uknown error occured")
}
} else
try {
val rdd = Source.fromFile(args(0)).getLines.toList.zipWithIndex.flatMap {
case(line, index) => line.split("\\W+").map { (_, index+1) }
} //filter(hardcodedkeywords.contains(_))
//.groupBy { _._1 }.mapValues(_._2)
} catch {
case ioe: IOException => println(ioe)
case fnf: FileNotFoundException => println(fnf)
case _: Throwable => println("Uknown error occured")
}
}
到目前为止,我已经设法使用 args(0) 包含要读取、要读取的文件并映射到包含每行字符串以及 index+1 的列表(因为行号从 1 开始,但索引从 0 开始)程序必须尽可能地具有功能性,以减少可变性和状态更改,并使用更多高阶函数和列表递归。
谢谢 示例输出将是:
//alphabetical //No duplicates
//order //Increasing in no.
keyword lines count
bar [1,2..] 6
foo [3,5] 2
hello [] 0
解决方案
这是如何完成的基本概述。
val keywords = List(/*key words here*/)
val resMap = io.Source
.fromFile(/*file to read*/)
.getLines()
.zipWithIndex
.foldLeft(Map.empty[String,Seq[Int]].withDefaultValue(Seq.empty[Int])){
case (m, (line, idx)) =>
val subMap = line.split("\\W+").toSeq //separate the words
.filter(keywords.contains) //keep only key words
.groupBy(identity) //make a Map w/ keyword as key
.mapValues(_.map(_ => idx+1)) //and List of line numbers as value
.withDefaultValue(Seq.empty[Int])
keywords.map(kw => (kw, m(kw) ++ subMap(kw))).toMap
}
//formatted results (needs work)
println("keyword\t\tlines\t\tcount")
keywords.sorted.foreach{kw =>
println(kw + "\t\t" +
resMap(kw).distinct.mkString("[",",","]") + "\t\t" +
resMap(kw).length
)
}
一些解释
io.Source
object
是提供一些基本输入/输出方法的库(实际上是一个),包括fromFile()
打开一个文件以供阅读。getLines()
一次从文件中读取一行。zipWithIndex
将索引值附加到读取的每一行。foldLeft()
一次读取文件的所有行,并且(在这种情况下)构建Map
所有关键字及其行位置的 a。resMap
并且subMap
只是我选择给我正在构建的变量的名称。resMap
(result Map) 是在处理整个文件后创建的。subMap
是由文件中的一行文本构建的中间 Map。
如果您想选择传递一组关键词,我会这样做:
val keywords = if (args.length > 1) args.tail.toList else hardcodedkeywords
推荐阅读
- mysql - 如果其中一个值在 Mysql 中有特定变量,如何改进选择范围
- protractor - 量角器中文本字段的值 - 未定义
- html - 如何均匀地间隔下拉框?
- c# - 如何在 c# Windows 窗体中将带十进制的文本框字符串转换为十进制。
- django - Django ORM 在一个查询中加入多对多关系
- amazon-web-services - AWS SQS 与单个工作人员?
- angular - 以角度 6 从 html 导出 Pdf
- python - df.plot.scatter 如何更改第二个 y 轴的大小?
- javascript - 在冲突之前创建引导日期选择器对象
- c# - 动态添加范围到列表