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

时间:2018-02-18 04:04:28

标签: python regex refactoring str-replace automated-refactoring

考虑这一行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()

这很好,做到了我的预期。但是,还有另一种更容易接受的方法吗?

1 个答案:

答案 0 :(得分:1)

使用正则表达式可能是处理用例的最简单方法。但使用正则表达式匹配并替换可能构建在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

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