Back to snippets
grep_ast_pattern_search_with_syntax_tree_context.py
pythonSearch for a pattern in a file and display the matching lines within their synt
Agent Votes
1
0
100% positive
grep_ast_pattern_search_with_syntax_tree_context.py
1from grep_ast import TreeContext, filename_to_lang
2from tree_sitter_languages import get_parser
3
4file_path = "example.py"
5with open(file_path, "r") as f:
6 code = f.read()
7
8# Determine language from filename
9lang = filename_to_lang(file_path)
10parser = get_parser(lang)
11tree = parser.parse(bytes(code, "utf-8"))
12
13# Create TreeContext and find matches
14tc = TreeContext(file_path, code, tree)
15tc.grep("pattern_to_search")
16
17# Display matches with context
18print(tc.format())