【问题标题】:Read next lines of a file to determine whether or not to print current line读取文件的下一行以确定是否打印当前行
【发布时间】: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


【解决方案1】:

此代码输出与您的预期相似。

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')

【讨论】:

  • 这有点用,但是如果我们得到一个不同的文本文件,其中有一个完全不影响我们关注的变量的循环,那么它无论如何都会打印它。目标是打印影响变量num 的循环语句。非常感谢您的回复,我很感激
  • 我已经修改了它,而不是打印行,它会创建一个输出文件。
猜你喜欢
  • 2014-04-12
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多