【问题标题】:Groovy: Extracting numbers from fileGroovy:从文件中提取数字
【发布时间】:2013-11-12 03:14:49
【问题描述】:

我有一个包含很多数字的列表,例如:

1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
...

如何逐行提取它们并进行一些计算? 类似(伪代码):

def f = new File("data.txt")
f.eachLine() {
    println(it.findAll( /\d+/ )*.toInteger()*2)
}

我需要去掉逗号和空格。

【问题讨论】:

  • 你快到了,你为什么停下来!? :P

标签: groovy


【解决方案1】:

这个怎么样?

def fileContent = new File('data.txt').text
def matches = fileContent =~ /\d+/
matches.each {
    println new Integer(it)*2
}

给予

2
4
6
8
10
12
14
16
18
20

【讨论】:

  • 当我用new File("data.txt") 替换这些数字时,我得到一个空输出。
  • 使用-> def fileContent = new File("data.txt").text
  • 看到评论了吗?此外,您的文件是否 100% 存在于该位置。只需运行 -> println(new File("data.txt").text) 即可对此进行测试。有时最好完全限定路径,即 new File("c:/test/data.txt")
【解决方案2】:

这个怎么样:

file.splitEachLine(/,\s+/){
        it.each(){
                println it.replace(/,/,'').toInteger() * 2
        }
}

如果文件的行尾没有逗号,则不需要替换。

【讨论】:

    【解决方案3】:

    您可以使用扫描仪从文件中读取所有数据。 Here是链接

    【讨论】:

    【解决方案4】:

    这里有一个帮助。我仍然相信可能有更好的方法:

    def list = []
    new File('data.txt').eachLine{
        list << it.replaceAll(/,/, '')
    }
    
    assert list*.replaceAll('\\s+', "")*.toInteger() == [12345, 678910]
    //or
    assert list.collect{it.replaceAll('\\s+', "").toInteger()} == [12345, 678910]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      相关资源
      最近更新 更多