我想在我的python代码中找到/使用除法运算符的所有实例.我的第一直觉是使用正则表达式.该表达式需要过滤掉/路径名称的非划分用法.我想出的最好的是[ A-z0-9_\)]/[ A-z0-9_\(].这将找到除法运算符
foo/bar
foo / bar
foo/(bar*baz)
foo / 10
1/2
etc...
Run Code Online (Sandbox Code Playgroud)
但也会匹配/s之类的东西"path/to/my/file"
任何人都可以提出更好的正则表达式吗?或者,是否有一种非正则表达方式来查找除法?
编辑:澄清:
我不一定需python要这样做.我只是想知道除法运算符的位置,所以我可以手动/视觉检查它们.我可以忽略评论的代码
您可以使用ast模块将Python代码解析为抽象语法树,然后遍历树以查找显示除法表达式的行号.
example = """c = 50
b = 100
a = c / b
print(a)
print(a * 50)
print(a / 2)
print("hello")"""
import ast
tree = ast.parse(example)
last_lineno = None
for node in ast.walk(tree):
# Not all nodes in the AST have line numbers, remember latest one
if hasattr(node, "lineno"):
last_lineno = node.lineno
# If this is a division expression, then show the latest line number
if isinstance(node, ast.Div):
print(last_lineno)
Run Code Online (Sandbox Code Playgroud)