如何自动计算和更改文本文件(Java类)中的数字?

时间:2013-10-14 19:07:44

标签: vim text-manipulation

假设我有一个类似the one from Oracle’s example的枚举类:

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    //...

我需要将班级中的所有数字乘以0.33。我不想在枚举中编写计算代码,而是要更改文本本身。在Vim / IDEA /任何其他工具中自动执行此操作的最快方法是什么?

3 个答案:

答案 0 :(得分:1)

使用vim,我会尝试以下方法:

:% s /\(\d\+\.\d\+\)/\=(submatch(1) * 0.33)/gc 

这将匹配整个文件中的每个数字(\ d +。\ d +)(%)并用(或=)匹配数字(submatch(1))的结果(\ =)替换它(s) 0.33。

答案 1 :(得分:1)

如果你走宏观路线,这是用自己的0.33代替视觉选择数字的一种方法:

c
<C-r>=
<C-r>"
*0.33
<CR>

答案 2 :(得分:0)

我切换到python这个。请考虑以下脚本:

#!/usr/bin/env python
import re

numeric_const_pattern = r"""
[-+]? # optional sign
(?:
    (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc
    |
    (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc
)
# followed by optional exponent part if desired
(?: [Ee] [+-]? \d+ ) ?
"""
rx = re.compile(numeric_const_pattern, re.VERBOSE)

with open('code.txt') as fd:
    for line in fd:
        num = rx.findall(line)
        for n in num:
            line = line.replace(n, str(float(n)*.33))
        print line.rstrip()

输出:

$ ./num.py 
public enum Planet {
    MERCURY (1.08999e+23, 805101.0),
    VENUS   (1.60677e+24, 1997094.0),
    EARTH   (1.97208e+24, 2104786.2),
    MARS    (2.11893e+23, 1121076.0),
    JUPITER (6.27e+26,   23592360.0),
    SATURN  (1.87704e+26, 19888440.0),
    URANUS  (2.86638e+25, 8434470.0),
    NEPTUNE (3.3792e+25, 8166180.0);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m0.99 kg-0.33 s-0.66)
    public static final double G = 2.20209e-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }

不完美,因为所有数字基本上都乘以0.33kg-1转换为kg-0.33等等。但这是一个开始。 下一步是忽略评论并减少误报......