搜索和编辑 python 源 (.py) 文件中的行



我想通过关键字匹配在python源代码文件(.py(中搜索特定行并编辑找到的行,还可以编辑前后行。所有这些都以编程方式进行,以便我可以自动化它。

是否有框架、工具或其他任何东西可以做到这一点?

更具体地说:

我必须装饰方法。我有一个列表(我已经转换为XML文件(所有方法及其关联的装饰器。由于我有 500 种方法,因此手动执行此操作也需要花费太多时间。这就是为什么我想找到一种实现自动化的方法。

例:

XML文件

<methods>
<method>
<name>method_1</name>
<decorator>xyz</decorator>
</method>
<method>
...
</methods>

源代码

在自动搜索结束编辑算法之前:

def method_1():
...

算法成功后:

@mark.xyz
def method_1():
...

那么按照这些思路呢,我包含一个replaceinsert函数,用于您需要为特定任务执行的任何操作。您也可以使用with来避免必须close并将其全部捆绑在那里,老实说,它可以使用更多的重构,但如果这不能满足您的需求,它不想走得太远。

*添加了 if 语句,如果您与关键字不匹配并返回错误,这将阻止您的整个文件被w选项擦除。

def find_edit(content, keyword):
for i in range(len(content)):
if content[i] == keyword:
previous_line = i -1
main_line = i 
post_line = i + 1 
return previous_line, main_line, post_line
def replace(position, replacer):
content[position] =  replacer
def insert(position, insertion):
content.insert(position, insertion)
filename = open('something.py', 'r')
content = filename.read().split('n')
prev, main, post = find_edit(content, 'line 3')
filename.close()
if prev and  main and post:
name = open('something.py', 'w')
something = '@mark.xyz'
replace(main, something)
prev, main, post = find_edit(content, 'another_line 2')
insert(post, something)
content = ('n').join(content)
name.write(content)
name.close()

输出

以前:

(xenial)vash@localhost:~/python/LPTHW$ cat something.py
line 1
line 2
line 3
some_line 1
some_line 2
some_line 3
another_line 1
another_line 2
another_line 3

之后:

(xenial)vash@localhost:~/python/LPTHW$ cat something.py
line 1
line 2
@mark.xyz
some_line 1
some_line 2
some_line 3
another_line 1
another_line 2
@mark.xyz
another_line 3

有没有框架、工具或其他任何东西来做到这一点?

在其他解决方案中,您可以使用Emacs

从常见问题

5.37 如何对多个文件执行替换操作?
Dired模式(M-x dired或C-x d(支持命令dired-do-find-regexp-and-replace (Q(,它允许用户替换多个文件中的正则表达式。

最新更新