[英]How to fetch line numbers for all 'if' 'else' and 'elif' positions in a python file
Example: Suppose, we have a.py file containing the below code snippet.示例:假设,我们有一个包含以下代码片段的 .py 文件。 How do we read and extract the positions of if-elif-else我们如何读取和提取if-elif-else的位置
If fisrtconditon:#line 1
If sub-condition:#line2
print(line no 3)
elif secnd_condn:#line 4
Xyz..#line5
Xyz..#line6
elif third condition:line7
...line 8
else:#line 9
Some content #line10***
Output: Output:
[1,4,7,9]
You can use the ast
module.您可以使用ast
模块。
import ast
with open('file.py') as f:
tree = ast.parse(f.read()) # parse the file
for node in ast.walk(tree): # walk the tree
if isinstance(node, ast.If): # if the node is an If (or an If-else)
print('If at line', node.lineno) # print the line number
if node.orelse: # if the node has an else
if isinstance(node.orelse[0], ast.If): # if the else is an If
print('Elif at line', node.orelse[0].lineno) # print the line number
else:
print('Else at line', node.orelse[0].lineno) # print the line number
ast is part of the standard library, so there's no need to install anything. ast 是标准库的一部分,所以不需要安装任何东西。 It stands for Abstract Syntax Tree, and it's a representation of the structure of your code.它代表抽象语法树,代表代码的结构。 You can find more information in the ast module documentation .您可以在ast 模块文档中找到更多信息。
A simple solution is to iterate over the lines of the file, using enumerate
to help you get the line number:一个简单的解决方案是遍历文件的行,使用enumerate
来帮助您获取行号:
with open("somefile.py") as f:
for line_no, line in enumerate(f, start = 1):
if line[:2] == "if" and (line[2].isspace() or line[2] == "("):
print(line_no, "if")
elif line[:4] == "elif" and (line[4].isspace() or line[4] == "("):
print(line_no, "elif")
elif line[:4] == "else" and (line[4].isspace() or line[4] == ":"):
print(line_no, "else")
Assumptions : this program assumes that somefile.py
has correct syntax.假设:这个程序假设somefile.py
有正确的语法。 Moreover, if this if
statement appears indented, for example, inside a function definition, it would not work.此外,如果此if
语句出现缩进,例如,在 function 定义中,它将不起作用。 The question's specifications did not dictate this requirement.问题的规范没有规定这个要求。
This program这个程序
"somefile.py"
for reading (the default mode of open
);打开文件"somefile.py"
进行读取(默认open
模式);enumerate
to get an index;遍历文件的行,使用enumerate
来获取索引; by default, indices will start from 0
but we specify the start
parameter so that it starts from 1
;默认情况下,索引将从0
开始,但我们指定start
参数,使其从1
开始;if
plus a (whitespace character or opening paren) or an elif
plus a (whitespace character or opening paren) or an else
plus a (colon :
or a whitespace character), then we print the line number as well as the corresponding if
, elif
, or else
.如果该行以if
加 a(空白字符或左括号)或elif
加 a(空白字符或左括号)或else
加 a(冒号:
或空白字符)开头,那么我们也打印行号作为相应的if
、 elif
或else
。with
block, Python closes the file for us.当我们退出with
块时,Python 会为我们关闭文件。Example例子
If somefile.py
is如果somefile.py
是
if condition:
if condition:
something
elif condition:
something
something
elif condition:
something
else:
something
then the above program outputs然后上面的程序输出
1 if
4 elif
7 elif
9 else
one-liner:单线:
indexes = [x+1 for x in range(len(content)) if any(x in ['if', 'elif', 'else'] for x in [list(content[x].lower().replace('#line',' ').replace(':',' ').split(' '))[0]])]
indexes:指标:
[1, 4, 7, 9]
The snipped below should do it:)下面的片段应该可以做到:)
#!/usr/bin/env python
# get_lines.py
def get_lines():
lines = []
with open('file.py') as f:
f = f.readlines()
for line in range(len(f)):
if f[line].startswith(('if', 'elif', 'else')):
lines.append(line + 1)
return lines
if __name__ == '__main__':
print(get_lines())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.