如何很好地阅读& quot;替代& amp;"线? [英] How to nicely read "alternating" lines?
问题描述
我有一个文本文件,其中包含遵循替代模式的行,例如:
I have a text file that contains lines that follow an alternate pattern, like:
name: SomeName
counterA: 0, counterB: 0, counterC: 0
name: SomeNameB
counterA: 1, counterB: 2, counterC: 3
...
我想编写一个简单的解析器来推送SameName,并将计数器A到C推送到一个新对象中.
I want to write a simple parser that pushes SameName, and the counters A to C into a new object.
因此,基本上,任务是总是一起处理两条行.
So the task is basically to process always two lines together.
我从以下代码开始:
fun readFileAsLinesUsingReadLines(fileName: String): List<String> = File(fileName).readLines()
fun main(args: Array<String>) {
val lines = readFileAsLinesUsingReadLines("Whatever")
for (i in (0 .. lines.size-1 step 2)) {
println(lines[i]+lines[i+1])
}
}
是的,可以打印
name: SomeName counterA: 0, counterB: 0, counterC: 0
然后我可以进一步解析.
which I can then further parse.
但是我发现(0 .. lines-size-1 step)
的用法不是很优雅.
But I find that usage of (0 .. lines-size-1 step)
to be not very elegant.
是否有更优雅或更多科特林"的方式来获取这些信息?
Are there more elegant, or "more kotlin" ways of pulling that information?
推荐答案
使用 chunked
,并带有一个转换lambda来解析和格式化您认为合适的内容:
With useLines
, you can read the lines as a (lazy) sequence, and then use chunked
with a transform lambda to parse and format as you see fit:
val result = File("file.txt").useLines { lines ->
lines.chunked(2) { (l1, l2) -> l1 + l2 }.toList()
}
result.forEach { println(it) }
如果出于某种原因要首先将所有内容流式传输到内存中,则还可以使用 chunked
:
If, for some reason, you want to stream everything into memory first, you can also use readLines
with the list-based version of chunked
:
val result = File("file.txt").readLines().chunked(2) { (l1, l2) -> l1 + l2 }
result.forEach { println(it) }
这篇关于如何很好地阅读& quot;替代& amp;"线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!