2017-07-30 58 views
0

我正在学习python的正则表达式。是否有更简单的方法来检查re.sub()是否替换了python中的单词?

我想检查一个文件中的文字是否被re.sub()函数替换。上述

import re 

original_file=open('original_file_path','r') 
replaced_file=open('replaced_file_path','w') 

compiled_pattern=re.compile('target_pattern') 

match_flag=False 
for line in original_file: 
    new_line=re.sub(compiled_pattern, 'new_pattern', line, flags=0) 
    replaced_file.write(new_line) 

    search_result=re.search(compiled_pattern, new_line) 
    if search_result: 
     match_flag=True 

original_file.close() 
replaced_file.close() 

if match_flag: 
    print("Some parts are replaced") 

我的代码使用re.search(),但我恐怕真的是多余的,因为应用re.sub和re.search扫描相同的“线”独立。 有没有更简单的方法来检查文件中的文字是否真的被替换?非常感谢你。

回答

1

re.subn

re.subn(pattern, repl, string, count=0, flags=0)

执行相同的操作sub(),但返回一个元组(new_string, number_of_subs_made)

例如:

>>> r = re.compile('a') 
>>> s = 'aaaaa' 
>>> (x,n) = re.subn(r, 'b', s) 
>>> n 
5 
>>> x 
'bbbbb' 
1

你可以比较旧与新的字符串

if new_line != line: 
    match_flag=True 
相关问题