2

假设我有一个像Oracle 示例中的枚举类:

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 / 任何其他工具中自动执行此操作的最快方法是什么?

4

3 回答 3

1

如果你走宏路线,这是用自身乘以 0.33 替换视觉选择的数字的一种方法:

c
<C-r>=
<C-r>"
*0.33
<CR>
于 2013-10-14T20:17:41.813 回答
1

使用 vim,我会尝试以下操作:

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

这将匹配整个文件 (%) 中的每个数字 (\d+.\d+) 并将其替换为 (s) 将匹配的数字 (submatch(1)) 乘以 (*) 乘以 0.33 的结果 (\=)。

于 2013-10-14T20:09:23.843 回答
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.33. kg-1变成kg-0.33等。但这是一个开始。下一步是忽略评论并减少误报...

于 2013-10-14T20:00:39.437 回答