python - 通过在文件内进行数学运算来编辑文本文件

标签 python text-files text-editor

我有一个像这样的文本文件(text.txt):

50  10  15  20  25
40  30  35  40  45
30  50  55  60  65

我已编辑此文件如下:

lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')

for line in lines:
    line = line.split()

    output.write('Values({},{},{},{},{});\n'.format(line[0], line[1], 
line[2], line[3], line[4]))

output.close()

这是新的文本文件:

Values(50,10,15,20,25);
Values(40,30,35,40,45);
Values(30,50,55,60,65);

现在我想通过对其组件进行数学运算来编辑文件(原始 text.txt):

  1. 我想从第一个中的所有分量中减去 10 栏目

  2. 我想从其余部分的所有分量中减去 1 栏目

更具体地说,我正在看这个:

Values(40,9,14,19,24);
Values(30,29,34,39,44);
Values(20,49,54,59,64);

如何在此文本文件中实现这个简单的数学运算以获得上述结果作为输出? 谢谢!

最佳答案

试试这个:

lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')

for line in lines:
    line = line.split()
    # subtract 10 from all of the components in the first column
    line[0] = int(line[0]) - 10
    # subtract 1 from all of the components in the rest of the columns
    line[1:] = [int(n) - 1 for n in line[1:]]
    output.write('Values({},{},{},{},{});\n'.format(*line))

output.close()

关于python - 通过在文件内进行数学运算来编辑文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51355425/

相关文章:

text-editor - 能够查看隐形的文本编辑器?

python - Pandas .agg 中的过滤计数

python - 为什么解构增强赋值不可能?

python - GtkWindow 一次只能包含一个小部件

C# 从以分号分隔的 .txt 文件获取数据

Java 文本文件从四列文本文件中删除 double

character - Redmine 中单个字符周围的粗体语法

python - 在 django 管理中点亮的下拉列表中过滤字段

c# - CheckedListBox - 如何以编程方式确保在任何给定时间只能选中一项?

javascript - 将内容发送到 WordPress 的纯文本编辑器