gpt4 book ai didi

python - 对于 AST 树中的每个子树,使用 Python 创建相应的列表

转载 作者:行者123 更新时间:2023-12-04 09:28:01 24 4
gpt4 key购买 nike

最近在做一个python代码抄袭检测项目。我从文献( https://www.researchgate.net/publication/221554617 )中学到了一个有趣的方法。在本文中,作者创建了一个特征向量,它是特定子树的数值近似。每个向量由节点的子向量的总和组成。
characteristic vectors with an AST
为此,我需要为每个子树创建一个 8 长度的列表,以便记录信息。 问题在于,列表和子树之间必须有对应关系,否则将毫无意义。 使用字典可能不是一个好方法,因为我需要遍历树。
理想情况下,我想获得一个新的存储结构,如 新节点它具有如下属性:



#Points to the current node(or sub-tree)
newnode.node

#The list corresponding to the node
newnode.vector

这是我的尝试(如果您愿意,可以忽略):
import ast
import numpy as np


class NewNode:
def __init__(self, node):
self.node = node
self.vector = np.zeros(8)


class Operation(ast.NodeTransformer):

def generic_visit(self, node):
ast.NodeTransformer.generic_visit(self, node)
new_node = NewNode(node)
print(type(node).__name__)
# the code below is an example of record ast.Store node-type
if isinstance(new_node.node, ast.Store):
new_node.vector[5] += 1


source = \
"""
a = 10
b = "test"
print(a)
"""
node = ast.parse(source)
k = Operation()
k.generic_visit(node)

最佳答案

你可以在节点上添加字段,这样你就可以做 node.vector = ...就在节点本身上,然后在访问树中的所有节点之后,将使用您想要应用的任何逻辑来表示向量。请注意 generic_visit需要return node或者访问者破坏了东西(假设您只想销毁该子树,则不返回任何内容)

import ast
import numpy as np

characteristics_map = {
# can just store the array for each node type, might be easier than case logic.
ast.Store: [0, 0, 0, 0, 0, 1, 0, 0],
}

class Operation(ast.NodeTransformer):

def generic_visit(self, node):
# you are allowed to add arbitrary fields to python objects
node.vector = np.zeros(8)
ast.NodeTransformer.generic_visit(self, node)
for a in ast.iter_child_nodes(node):
# this node will be sum of all children nodes
# as well as case logic below.
node.vector += a.vector

if type(node) in characteristics_map:
node.vector += np.array(characteristics_map[type(node)])
return node


source = \
"""
a = 10
b = "test"
print(a)
"""
node = ast.parse(source)
k = Operation()
k.generic_visit(node)
# there are 2 stores so the 5th element has a value of 2
print(node.vector)

关于python - 对于 AST 树中的每个子树,使用 Python 创建相应的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62942927/

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