[英]Insert text on specific positions with notepad++ python script plugin
[英]I need help to round numbers for currency conversion in a text file using notepad++ and python script plugin
有人可以帮助我会很好。
我有看起来像这样的文本文件:
#Zsdfgsdqfq
#A100,56
#Zjtdhsdfg
#Zadsdf
#B12,53
#Zdwfgs
#C10,00
#Zdsfgdfg
#D40,00
在文件#A,#B,#C和D#中,我需要除以6.55957的数字是我想要的结果:
#A15,33
#Zjtdhsdfg
#Zadsdf
#B1,91
#Zdwfgs
#C1,52
#Zdsfgdfg
#D6,10
我发现了这个有用的讨论: 记事本++如何将大量替换中的数字相乘?
所以我在Notepad ++中使用了Python脚本插件
我无法弄清楚如何管理小数点和用于小数点分隔符的逗号。
我发现我可以删除所有逗号,然后将结果除以100,然后就能搜索并替换以逗号替换结果文件中的点。
这是基于我在链接讨论中所读内容的脚本:
def multiply_number_in_context(match):
return "{0}{1}".format(match.group(1), str(int(match.group(2))/655.957)) # thank you Wiktor Stribiżew to explain me how to get rid of this : ,''
editor.rereplace(r'(\#A)(\d+)', multiply_number_in_context)
editor.rereplace(r'(\#B)(\d+)', multiply_number_in_context)
editor.rereplace(r'(\#C)(\d+)', multiply_number_in_context)
editor.rereplace(r'(\#D)(\d+)', multiply_number_in_context)
结果如下:
#Zsdfgsdqfq
#A15.33027317339399
#Zjtdhsdfg
#Zadsdf
#B1.910186185984752
#Zdwfgs
#C1.524490172374104
#Zdsfgdfg
#D6.097960689496415
它可以工作,但是现在我需要将结果四舍五入为两个小数。 #A应该为15.33,#D应该为6.10
看来方法是使用round(x,2)东西,但我无法确定ho能否使此工作生效。
我试图用这种东西来修改我的脚本:
return "{0}{1}{2}".format(match.group(1), str(round(int(match.group(2))/655.957), '')), 2)
或修改脚本,使它四舍五入而不是乘以数字,但没有成功,我遇到语法错误等。
如果有人可以改善我的脚本,以便对结果进行四舍五入,或者给我另一个可以对结果进行四舍五入的脚本,那将是一种好感。
我不想学习编程,我只是在寻找解决方案。
谢谢。
使用以下固定脚本:
def multiply_number_in_context(match):
return "{0:.2f}".format(float(match.group(0).replace(',', '.'))*100.0/655.957).replace(".",",")
editor.rereplace(r'(?<=#[A-Z])\d+(?:,\d+)?', multiply_number_in_context)
参见regex演示 。 细节:
(?<=#[AZ])
-在正后方匹配,匹配的位置是紧跟#
的位置,然后匹配任何大写ASCII字母(更改为[AD]
以仅匹配A
, B
, C
或D
) \\d+
-1个以上数字 (?:,\\d+)?
-匹配的可选子字符串
,
-逗号 \\d+
-1个或多个数字。 结果:
笔记
match.group(0).replace(',', '.')
用点替换逗号以简化计算 float(...)*100.0/655.957
将找到的数字float(...)*100.0/655.957
为float,然后乘以100再除以655.957 "{0:.2f}".format(...)
-格式化浮点舍入结果 .replace(".",",")
-恢复十进制分离器,
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.