【发布时间】:2021-06-06 22:03:15
【问题描述】:
我正在尝试用 python 编写这个程序切片器程序,但这一点点花了我很长时间才弄明白。
我想逐行读取某个文件,并且只打印影响某个变量的行。
在这种情况下num
这是我正在读取的文本文件:
a = 3
b = 4
num = 0
while a > b:
if a > b:
a = a +2
b = b + 1
if a > 2:
num-=1
我的 python 文件必须读取这个文件 ^ 并且它必须通过打印包含变量 num 的行和 num 所在的循环语句来隔离变量 num。
这是我期望的输出:
num = 0
while a > b:
if a > b:
if a > 2:
num-=1
到目前为止,这是我的代码,负责读取循环内行的代码部分不起作用:
# Open file
file = open('text.py', 'r')
Lines = file.readlines()
count = 0
word = "num"
# Store all the loop statements that can appear in the file
keyword = ["while", "for", "if", "else", "elif", "def"]
for i in range(len(Lines)):
count += 1
# if line contains keyword
if any(word in Lines[i] for word in keyword):
# read lines inside the loop
# count_indent is a function that counts the indent of the line to compare it and see if the line is inside the loop or not. I didn't added to the question shorter
line_indent = count_indent(Lines[i])+4
while i <= len(Lines) and count_indent(Lines[i + 1]) == line_indent:
# if word appears in the next lines that are inside the loop then we print the loop statement
if word in Lines[i + 1]:
print(str(count) + " : " + Lines[i])
else:
break
# move to next line inside the loop
i = i + 1
# If line is not empty and contains word
if Lines[i] != '\n' and word in Lines[i]:
print(str(count) + " : " + Lines[i])
【问题讨论】:
-
尝试读取文件,明确说明 \n 是行分隔符 file = open('text.py', 'r', newline = '\n')
-
你想要的是一个合适的解析器。查看
ast模块。
标签: python while-loop