gpt4 book ai didi

python - 重构 python 代码以更改名称

转载 作者:行者123 更新时间:2023-11-28 19:06:10 25 4
gpt4 key购买 nike

我有一个不遵循命名约定的 python 项目,即“变量和函数名称是 snake_case”,它们是使用 C# 约定“CamelCase”编写的。我试过使用 RegEx 来更改这些名称,但结果不准确。 Here我使用 AST 树来更改名称。我找不到任何有用的示例来帮助我理解如何更改 AST 树中的节点然后将其重写回来。

我尝试的最终代码如下,其中我尝试先将名称更改为小写

    import ast
import astunparse


def byter(src):

class RewriteStr(ast.NodeTransformer):
def generic_visit(self, node):
print("inside generic", type(node).__name__)

ast.NodeVisitor.generic_visit(self, node)
return node

def visit_Str(self, node):
print("visiting a str node", type(node).__name__)
return ast.Bytes(node.s.encode('ascii'))

def visit_FunctionDef(self, node):
print("inside def", type(node).__name__)
return ast.FunctionDef(name=node.name.lower())

def visit_Call(self, node):
print("inside call", type(node).__name__)
if hasattr(node.func, "value"):
print(ast.dump(node.func.value))
return ast.copy_location(ast.Call(func=ast.Name(id=node.func.value.id.lower())), node)

def visit_Name(self, node):
print("name ", type(node).__name__, ast.dump(ast.Name(id=node.id.lower(), ctx=node.ctx)))
return ast.copy_location(ast.Name(id=node.id.lower(), ctx=node.ctx), node)

tree = ast.parse(src)
tree = RewriteStr().visit(tree)
ast.fix_missing_locations(tree)
# get back the source code


# get a pretty-printed dump of the AST


print(ast.dump(tree))
print(astunparse.unparse(tree))
out = open("C:\\Users\\pc1\\Desktop\\output.txt", "w", encoding="UTF-8")


tree = open("C:\\Users\\pc1\\Desktop\\sampl.py", encoding="UTF-8").read()
byter(tree)

输入文件是

    import FooFOo

DATA = open('file') # a function call

FooFoo.bar(arg=data) # a function call

FooFoo.bar(arg=foo.meow(foo.z(arg=data))) # three function calls

FooFoo.WooF(foo.x.y(arg=data))
def FunC():
print("foo foo")

当我在转换器完成后打印树时,节点没有改变。我从一开始就做错了吗?这是 AST 树的正确用法吗?有没有一种方法可以重命名 python 代码中的函数和变量,而不是更准确、更轻松的方法?

最佳答案

虽然您可能从 9 月开始就离开了这个项目,但您应该看看 Rope用于 Python 重构,这将比 AST 树更准确且更轻松。

正如评论中提到的:各种 IDE 都有自己的重构功能,使用内置功能通常是一个合理的决定。如果您使用的是 emacs 或 vim,则可以直接使用 Rope。

关于python - 重构 python 代码以更改名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46362714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com