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

2024-04-25 08:14:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望通过关键字匹配在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():
  ...

Tags: 文件方法namepy算法编辑源代码def
2条回答

关于这方面的内容,我包括了一个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

Is there a framework, tool or anything else to do that?

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

FAQ

5.37 How do I perform a replace operation across more than one file?
Dired mode (M-x dired , or C-x d) supports the command dired-do-find-regexp-and-replace (Q), which allows users to replace regular expressions in multiple files.

相关问题 更多 >