Skip to main content
 首页 » 编程设计

python之替换脚本中的函数调用的最佳方法是什么

2025年01月19日7kuangbin

考虑这行 Python:

new_string = change_string(old_string) 

如果您想替换或删除函数调用并且只有 new_string = old_string,简单的文本替换是不够的。 (用空字符串替换“function_changes_string(“将留下右括号。如果你想替换函数调用 100 次或更多次怎么办。那会浪费很多时间。

作为替代方案,我使用正则表达式来替换函数调用。

这是一个简短的 python 脚本,它将要删除的函数的名称作为输入。

import os 
import re 
 
# Define variables 
current_directory = os.getcwd() 
file_to_regex_replace = "path/to/script/script.py" 
output_filepath = current_directory + "/regex_repace_output.py" 
regex_to_replace = re.compile(r"function_changes_string\((.+?)\)") 
fixed_data_array = [] 
 
#read file line by line to array 
f = open(file_to_regex_replace, "r") 
data = f.readlines() 
f.close() 
 
line_count = 0 
found_count = 0 
not_found_count = 0 
for line in data: 
    line_count += 1 
    # repace the regex in each line 
    try: 
        found = re.search(regex_to_replace, line).group(1) 
        found_count += 1 
        print str(line_count) + " " + re.sub(regex_to_replace, found, line).replace("\n", "") 
        fixed_data_array.append(re.sub(regex_to_replace, found, line)) 
    except AttributeError: 
        fixed_data_array.append(line) 
        not_found_count += 1 
 
print "Found : " + str(found_count) 
print "Total : " + str(not_found_count + found_count) 
 
# Open file to write to 
f = open(output_filepath, "w") 
 
# loop through and write each line to file 
for item in fixed_data_array: 
    f.write(item)  
f.close() 

这工作正常并且达到了我的预期。但是,是否有另一种更容易接受的方法来做到这一点?

请您参考如下方法:

使用正则表达式可能是处理用例的最简单方法。但使用正则表达式匹配和替换可能内置于您的 IDE 中的功能,而不是通过编写您自己的脚本来重新发明轮子。

请注意,许多 IDE 在应用程序中内置了强大的自动重构功能。例如,PyCharm 理解 extracting method calls 的概念以及重命名变量/方法、更改方法签名和 several others .但是,PyCharm 目前没有针对您的用例的内置重构操作,因此正则表达式是一个不错的选择。

这是一个适用于 Atom 的正则表达式示例:

Find:      change_string\((.+)\) 
Replace:   $1 

给定 new_string = change_string(old_string) 行,替换后的结果行将是 new_string = old_string。

如果您正在为一家代码库相对较大的公司编写软件,那么大规模重构操作可能会频繁发生,以至于该公司已经针对您的用例开发了自己的解决方案。如果可能是这种情况,请考虑询问您的同事。