python使用tree-sitter库简单上手安装入门教程

本文介绍了如何在Python中使用Tree-Sitter创建环境,安装依赖,以及通过克隆和构建解析器库来解析C和C++源代码。作者还展示了如何在在线平台上测试和验证树形解析器的工作效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tree-sitter在线体验网站

https://tree-sitter.github.io/tree-sitter/playground

在通过python使用tree-sitter之后,我们可以通过上面的网站熟悉一下tree-sitter的功能和性能。

step1 创建环境

首先我们创建一个conda环境,并激活
例如我创建的是名称为treesitter的conda环境,python版本是3.9

conda create -n treesitter python=3.9
conda activate treesitter

step2 安装依赖

使用pip安装tree-sitter 的依赖,等待完成即可

pip install tree-sitter

step3 新建项目

我们新建一个 python 的项目,使用刚刚创建好的环境。

(1) 克隆解析器

首先我们到根目录下,创建一个名为vendor 的文件夹。

然后将我们需要解析的源代码语言的对应解析器项目代码给 git clone 下来。

例如,我想用tree-sitter来解析 C 语言和 C++ 语言的源代码,那么我就需要从github上克隆下来tree-sitter-ctree-sitter-cpp 这两个库

git clone https://github.com/tree-sitter/tree-sitter-c.git
git clone https://github.com/tree-sitter/tree-sitter-cpp.git

在这里插入图片描述

(2)创建build.py

完成克隆后,我们在根目录创建一个名为build.py 的文件,里面写入:

from tree_sitter import Language

Language.build_library(

  # Store the library in the `build` directory
  'build/my-languages.so',

  # Include one or more languages
  [
    'vendor/tree-sitter-c',
    'vendor/tree-sitter-cpp'
    # 'vendor/tree-sitter-java',
    # 'vendor/tree-sitter-python',
    # 'vendor/tree-sitter-cpp',
  ]
)

注意,在上面的数组[]里,我们写上需要的解析器项目的路径,我需要解析c和cpp语言,那么我就写了 'vendor/tree-sitter-c' 'vendor/tree-sitter-cpp'这两个,当然如果需要其他语言,就换成对应语言的解析器的地址就行啦。

我们 运行 写好的build.py文件,会生成一个名为build/的文件夹。

在这里插入图片描述

4. 测试

然后,我们在根目录创建一个main.py文件,填入以下内容
代码部分参考自👉 python环境解析任意语言tree-sitter的使用方法

from tree_sitter import Language, Parser

# 注意C++对应cpp,C#对应c_sharp(!这里短横线变成了下划线)
# 看仓库名称
CPP_LANGUAGE = Language('build/my-languages.so', 'cpp')
#CS_LANGUAGE = Language('build/my-languages.so', 'c_sharp')

# 举一个CPP例子
cpp_parser = Parser()
cpp_parser.set_language(CPP_LANGUAGE)

# 这是b站网友写的代码,解析看看
cpp_code_snippet = '''
int mian{
  piantf("hell world");
  remake O;
}
'''

# 没报错就是成功
tree = cpp_parser.parse(bytes(cpp_code_snippet, "utf8"))
# 注意,root_node 才是可遍历的树节点
root_node = tree.root_node

print(root_node)
print('ok')

如果跑起来有显示,说明环境成功了~

在这里插入图片描述

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值