我有以下测试文件
testfile1输出:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
#commented out
testfile2输出:
import difflib
with open('testfile1') as text1, open('testfile2') as text2:
diff = difflib.ndiff(text1.readlines(), text2.readlines())
with open('diff.txt', 'w') as result:
for line in diff:
result.write(line)
我想比较两个文件并仅打印差异输出。如果行开头的任何注释忽略比较那些行。
以下是我尝试的代码:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
+ #commented
输出:
put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
预期产出:
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,retain) UILabel *mylabel;
@property (nonatomic,retain) UIButton *myButton;
@end
@implementation ViewController
@synthesize mylabel,myButton;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
mylabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height*0.11, self.view.frame.size.width, 30)];
mylabel.translatesAutoresizingMaskIntoConstraints=false;
[mylabel setTextAlignment:NSTextAlignmentCenter];
mylabel.text = @"Button Not Pressed";
[self.view addSubview:mylabel];
myButton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height*0.13, self.view.frame.size.width, 50)];
myButton.translatesAutoresizingMaskIntoConstraints=false;
[myButton setTitle:@"Button" forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(buttonHandler:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];
}
-(void) buttonHandler:(UIButton*)sender{
mylabel.text = @"ButtonPressed";
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
并打印"无变化"
答案 0 :(得分:1)
我会使用列表解析消除#
- 标记的行:
...
with open('testfile1') as text1, open('testfile2') as text2:
diff = difflib.ndiff(
[line for line in text1 if not line.startswith('#')],
[line for line in text2 if not line.startswith('#')]
)
...