我想找到我的所有实例python
除法运算符的代码/
用来。我的第一直觉是使用正则表达式。该表达式需要过滤掉非除法的使用/
,即路径名。我想出的最好的是[ A-z0-9_\)]/[ A-z0-9_\(]
。这将找到除法运算符
foo/bar
foo / bar
foo/(bar*baz)
foo / 10
1/2
etc...
但也会匹配/
是这样的"path/to/my/file"
有人能想出更好的正则表达式吗?或者,是否有非正则表达式的方法来查找除法?
编辑:澄清:
我不一定需要使用python
去做这个。我只想知道除法运算符的位置,以便我可以手动/目视检查它们。我可以忽略注释代码
您可以使用以下命令将 Python 代码解析为抽象语法树:ast模块,然后遍历树找到出现除法表达式的行号。
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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)