简体   繁体   English

groovy 从文件中读取数据

[英]groovy read data from file

I need some help with reading data from txt file.我需要一些帮助来从 txt 文件中读取数据。 I want to indicate if line is inside 'project' section.我想指出行是否在“项目”部分内。 And if so look for com.google.maps.api:1.9.10 .如果是这样,请查找com.google.maps.api:1.9.10 I should get information whether it is in project section.我应该得到信息是否在project部分。 I don't provide here any source code, because I don't have an idea how to think about this situation.我在这里不提供任何源代码,因为我不知道如何考虑这种情况。 Maybe you have any idea how to resolve this.也许你知道如何解决这个问题。

Sample input:样本输入:

Below example data from file:以下来自文件的示例数据:

+--- project :google-json
|    +--- other data
|    +--- other data
|    +--- com.google.maps.api:1.9.10
|    +--- other data
+--- something :google-json
|    +--- other data
|    +--- other data
|    +--- com.google.maps.api:2.2.2
|    +--- other data

First idea here is to loop over the lines splitted with new line character ( \\n ) then check if you're in appropriate section and then verify if any subsequent line contains the wanted value.这里的第一个想法是遍历用换行符 ( \\n ) 分割的行,然后检查您是否在适当的部分,然后验证是否有任何后续行包含所需的值。 If so it's found, otherwise it's not.如果是,它被发现,否则它不是。

The second idea is to use more data oriented approach.第二个想法是使用更多面向数据的方法。 Use the regex to split data into sections, then transform them to tuples and look for a tuple with appropriate name which will have the wanted value in it's value.使用正则表达式将数据拆分为多个部分,然后将它们转换为元组并查找具有适当名称的元组,该元组将在其值中包含所需的值。 Here's how it goes:这是它的过程:

def input = '''
+--- project :google-json
|    +--- other data
|    +--- other data
|    +--- com.google.maps.api:1.9.10
|    +--- other data
+--- something :google-json
|    +--- other data
|    +--- other data
|    +--- com.google.maps.api:2.2.2
|    +--- other data
'''
input
    .split(/(?ms)(^\+--- )/)
    .toList()
    .findAll { !it.trim().isEmpty() }
    .collect {
        def section = it.substring(0,it.indexOf('\n'))
        new Tuple(
            section,
            (it - section)
            .trim()
            .split('\n')
            .collect { (it - '|    +---').trim() }
        )
    }
   .find {
       it.get(0) == 'project :google-json' && it.get(1).find { 'com.google.maps.api:1.9.10'.equals(it) }
   }
  1. Split lines with appropriate regex - here, a line with that starts with +--- is a delimiter.使用适当的正则表达式拆分行 - 此处,以+---开头的行是分隔符。
  2. Since split returns array, turn it int list.由于 split 返回数组,因此将其转为 int 列表。
  3. Remove all empty elements.删除所有空元素。
  4. Transform data into tuples.将数据转换为元组。 The first value is section name (eg project :google-json ), the second is a list of dependencies with ASCII art tree elements removed.第一个值是部分名称(例如project :google-json ),第二个值是删除了 ASCII 艺术树元素的依赖项列表。
  5. Find the wanted tuple.找到想要的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM