簡體   English   中英

讀取文件的下一行以確定是否打印當前行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM