Groovy从文本行创建地图 [英] Groovy create map from lines of text
问题描述
我有3个单独的行中包含的原始数据.我想使用每行的一部分来构建单个地图记录.然后,我阅读接下来的3行并创建下一个地图记录,依此类推.我在地图上找到的所有常规示例都显示它们是由单行数据创建的,或者可能是我误解了这些示例.这是原始数据的样子.
I have raw data that is contained in 3 separate lines. I want to build a single map record using parts of each line. I then read the next 3 lines and create the next map record and so on. All the groovy examples I've found on maps show them being created from data on a single line, or possibly i am misunderstanding the examples. Here is what the raw data looks like.
snmp v2: data result = "Local1"
snmp v2: data result ip = "10.10.10.121"
snmp v2: data result gal = "899"
new
snmp v2: data result = "Local2"
snmp v2: data result ip = "192.168.10.2"
snmp v2: data result gal = "7777"
new
我想将此数据放入地图.在此示例中,Local1和Local2将是键,并且它们各自具有2个关联值.我将向您展示我的最新尝试,但这仅是一个失败的猜测.
I want to put this data into a map. In this example Local1 and Local2 would be keys and they would each have 2 associated values. I will show you my latest attempt but it is little more then a guess that failed.
def data = RAW
def map = [:]
data.splitEachLine("="){
it.each{ x ->
map.put(it[0], it[1])
map.each{ k, v -> println "${k}:${v}" } }}
所需的输出是:
[ Local1 : [ ip: "10.10.10.121", gal: "899" ],
Local2: [ ip: "192.168.10.2", gal: "7777" ] ]
推荐答案
如果您想获得dmahapatro建议的嵌套地图,请尝试以下操作:
If you want to get a nested map as suggested by dmahapatro try this:
def map = [:]
data=data.eachLine() { line ->
if(line.startsWith("new")) return
tokens=line.replace("snmp v2: data","").split("=")
tokens=tokens.collect() { it.trim().replace("result ","").replaceAll(/"/, "") }
if(tokens[0]=="result") {
nested=[:]
map[tokens[1]]=nested
}
else
nested[tokens[0]]=tokens[1]
}
println("map: $map")
我们在这里:
- 重复行
- 跳过开头为"new"的行
- 从该行的文本中删除"snmp v2:数据"
-
将每行分割为令牌,trim()每个令牌,并删除结果"和引号 令牌成对出现,现在看起来像:
- iterate over lines
- skip lines with "new" at the beginning
- remove "snmp v2: data" from the text of the line
split each line in tokens, trim() each token, and remove "result " and quotes tokens are in pairs and now look like:
结果,本地1
ip,10.10.10.121
ip, 10.10.10.121
gal,899
接下来,当第一个标记为结果"时,我们将构建一个嵌套地图,并将其放置在主地图中,标记为token [1]的值所给定的键.
next when the first token is "result", we build a nested map and place in the main map at the key given by the value of token[1]
结果是:
map: [Local1:[ip:10.10.10.121, gal:899], Local2:[ip:192.168.10.2, gal:7777]]
修复删除引号
这篇关于Groovy从文本行创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!