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

Python 替换脚本中的函数调用的最佳方法是什么?,python,regex,refactoring,str-replace,automated-refactoring,Python,Regex,Refactoring,Str Replace,Automated Refactoring,考虑Python的这一行: new_string = change_string(old_string) 如果您想要替换或删除函数调用,并且只使用new\u string=old\u string,那么简单的文本替换是不够的。(将“function_changes_string”()替换为空字符串将留下右括号。如果您想替换函数调用100次或更多次,该怎么办?这是浪费大量时间 作为替代,我使用正则表达式替换函数调用 下面是一个简短的python脚本,它以要删除的函数名作为输入 import os

考虑Python的这一行:

new_string = change_string(old_string)
如果您想要替换或删除函数调用,并且只使用
new\u string=old\u 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了解变量/方法的概念,以及重命名变量/方法、更改方法签名等。但是,PyCharm目前没有针对您的用例的内置重构操作,因此regex是一个很好的替代方案

下面是一个在以下情况下工作的示例正则表达式:

给定行
new\u string=change\u string(old\u string)
,替换后的结果行将是
new\u string=old\u string


如果你正在为一个相对大的代码库的公司编写软件,那么大规模的重构操作可能会频繁发生,以至于公司已经开发出了自己的用例解决方案。如果是这样的话,考虑问问你的同事。

我使用的IDE是Atom,它有ReGeX替换。进行了快速搜索,找到了使用正则表达式捕获的方法。->
Find:      change_string\((.+)\)
Replace:   $1