逻辑的文件进行比较逻辑、文件

2023-09-11 05:51:28 作者:ー個亽の江湖

我想写一个PROGRAMM的文件进行比较。例如:

I trying to write a programm for file compare. For example:

文件1

1
2
3
4
5

文件2

1
2
@
3
4
5

如果我这样做,一行行,我得到:

If I do it line by line, I get:

1 == 1; 
2 == 2;
3 != @;
4 != 3;
5 != 4;
  != 5;

不过,事实是,文件之间唯一的区别是@。我想要得到的东西是这样的:

But, the truth is that the only difference between the files is @. I want get something like this:

1 == 1;
2 == 2;
  != @;
3 == 3;
4 == 4;
5 == 5;

这是做到这一点的最好方法是什么?无需使用任何外部应用程序,如差异,FC等

Which is the best way to do it? without using any external application, such as diff, fc, etc.

推荐答案

Python有一个非常方便的库比较序列称为的 difflib 。底层SequenceMatcher类有两个蟒蛇序列,给你(除其他事项外)运codeS序列告诉你,你会如何从第一个序列的第二个(即差异)。这些都是形式:

Python has a very handy library for comparing sequences called difflib. The underlying SequenceMatcher class takes two python sequences and gives you (among other things) a sequence of opcodes telling you how you would get from the first sequence to the second (i.e. the differences). These are of the form:

有一个替换此块 插入块 删除块 复制块(称为'等于')

通过给指数成原始序列,这些参考块。这可以应用到文件中的行或字符串中的字符或其他任何东西,你可以变成Python中的顺序。

These reference blocks by giving indices into the original sequences. This can be applied to lines in a file or characters in a string or anything else you can turn into a sequence in python.