【问题标题】:Multiply numbers in mass replace在大量替换中乘以数字
【发布时间】:2021-02-16 13:45:52
【问题描述】:

我正在使用 notepad++ 编辑 YAML 文件,并且由于 NPP 无法使用算术替换数字,我认为也许 python 脚本可以完成这项工作(在 NPP 中使用 PythonScript 插件)。问题是,我在 python 方面非常糟糕,我无法让它工作。我想要做的是将“收入:”后面的所有数字乘以 10:

income: 0.5
points: 0.15
experience: 0.3

我已尝试运行此脚本:

def multiply_number_in_context(match):
    return "{0}{1}{2}".format(match.group(1), str(float(match.group(2))*10), '"')

editor.rereplace(r'(income: )(\d+)', multiply_number_in_context)

但它返回以下内容:

        income: 0.0".5
        points: 0.15
        experience: 0.3

对此有什么帮助吗?谢谢!

【问题讨论】:

  • \d 仅匹配数字,因此您的匹配不包括小数点和最后 5。对第二个捕获组使用类似 ([0-9.]+) 的内容。
  • 我不太明白第二段的目的。对我来说,这看起来不仅仅是一个简单的算术命令。解决方案应该简单且最大。 10行代码

标签: python notepad++


【解决方案1】:

算术运算的python解应该是这样的:

#Define your current list
income = [0.5, ...]

#Define your goal
income = [i * 10 for i in income]

#Print the results
print(income)

【讨论】:

  • 顺便说一句,OP 要求提供 PythonScript
【解决方案2】:

这行得通。使用 NPP v7.8.7 64bit 测试。

import re

pattern = r"(?<=income: )([^\n]*)"

def func(match):
    return 10 * float(match.group(1))

editor.rereplace(pattern, func)

使用 Positive lookahead 匹配前面的标记,但不包括在结果中。

这样你只匹配它后面的标记,无需替换整行。

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 2012-08-23
    • 2010-12-27
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2010-10-19
    • 2021-07-01
    • 2019-05-20
    相关资源
    最近更新 更多