打印起点和终点之间的线条

2024-05-19 00:04:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这样一个文本文件:

***a
foo bar
lorem ipsum
dolor
---a

我想打印***a---a之间的行,我正试图用这个:

^{pr2}$

但它在一个无限循环中打印***a。我怎么解决这个问题?在


Tags: foobar文本文件ipsumloremdolor正试图pr2
3条回答

如果多次出现,则可以在到达起始线时启动内部循环,这相当于while尝试执行的操作:

with open("test.txt") as f:
    for line in f:
        if line.rstrip() == "***a":
            print("")
            for line in f:
                if line.rstrip() == " -a":
                    break
                print(line.rstrip())

用于:

^{pr2}$

将输出:

foo bar
lorem ipsum
dolor

bar bar
foobar
foob

如果您想要没有换行符的行,我们可以map将其关闭,然后继续逐行迭代:

with open("test.txt") as f:
    # itertools.imap python2
    f = map(str.rstrip, f)
    for line in f:
        if line == "***a":
            print("")
            for line in f:
                if line == " -a":
                    break
                print(line)

使用breakcontinue

def printlines():
    pattern = open('text.txt').read().splitlines()
    for line in pattern:
        if line == "***a":
           continue
        if line == " -a":
           break
        print line

中断

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

继续

The continue statement, also borrowed from C, continues with the next iteration of the loop.

使用状态机。这意味着,一旦你看到你的开场白,就要设置一个状态,这样你就知道下面几行与你有关了。然后继续寻找结束模式来关闭它:

def printlines():
    # this is our state
    isWithin = False

    with open('text.txt') as f:
        for line in f:
            # Since the line contains the line breaking character,
            # we have to remove that first
            line = line.rstrip()

            # check for the patterns to change the state
            if line == "***a":
                isWithin = True
            elif line == " -a":
                isWithin = False

            # check whether we’re within our state
            elif isWithin:
                print line

因为我们只在isWithin状态下打印,所以我们可以很容易地跳过***a/ -a模式之外的任何部分。因此,处理以下文件将正确地输出Hello和{}而不输出其他内容:

^{pr2}$

另外,您应该使用with语句打开文件,并直接迭代file对象,而不是读取它并调用splitlines()。这样可以确保文件被正确地关闭,并且只读取一行又一行的内容,从而提高内存效率。在

相关问题 更多 >

    热门问题