[英]Read next lines of a file to determine whether or not to print current line
我正在尝试在 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
。 这是我期望的 output:
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])
此代码 output 与您的预期相似。
file = open('text.py', 'r', newline = '\n')
lines = file.readlines()
word = "num"
keyword = ["while", "for", "if", "else", "elif", "def"]
with open('out_text.py', 'wt') as fout:
for line in lines:
if any(word in line for word in keyword):
fout.write(line + '\n')
elif word in line:
fout.write(line + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.