简体   繁体   English

Python从输出变量中搜索字符串并打印下两行

[英]Python search string from output variable and print next two lines

How do I Search string from command output and print next two lines from the output. 如何从命令输出中搜索字符串并从输出中打印下两行。

Below is code: 以下是代码:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
for line in a.split("\n"):
    if line.startswith("----"):
        print "I need this line"
        print "I need this line also"

What I am doing in above code is I am checking if line starts with "----" and This works fine. 我在上面的代码中做的是我正在检查行是否以“----”开头,这样可以正常工作。 Now How do i print exactly two lines after line starts with "----". 现在如何在行开头后用“----”打印两行。 In this example code print, " I need this line and I need this line also" 在这个代码打印示例中,“我需要这条线,我也需要这条线”

you can create an iterator out of the list (no need with a file handle BTW). 你可以从列表中创建一个迭代器(不需要文件句柄BTW)。 Then let for iterate, but allow to use next manually within the loop: 然后让for迭代,但允许使用next手动的循环中:

a = """
Some lines I do not want
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
my_iter = iter(a.splitlines())
for line in my_iter:
    if line.startswith("----"):
        print(next(my_iter))
        print(next(my_iter))

This code will raise StopIteration if there aren't enough lines after the dashes. 如果破折号后面没有足够的行,此代码将引发StopIteration One alternative that avoids this issue is (courtesy Jon Clements) 避免这个问题的另一种选择是(Jon Clements提供)

from itertools import islice

my_iter = iter(a.splitlines(True))  # preserves \n (like file handle would do)
for line in my_iter:
    if line.startswith("----"):
        print(''.join(islice(my_iter, 2)))

Another way, without splitting the string: 另一种方法,不拆分字符串:

print(re.search("-----.*\n(.*\n.*)",a).group(1))

this searches for 2 lines after the pattern in the unsplitted , multi-line string. 这将在未分割的多行字符串中的模式之后搜索2行。 Can crash if re.search returns None because there are no more lines. 如果可能崩溃re.search返回None ,因为没有更多的线路。

In both cases you get: 在这两种情况下,你得到:

I need this line
I need this line also

This is one simple way: 这是一个简单的方法:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""

lines = a.split("\n")
for i in range(len(lines)):
    if lines[i].startswith("----"):  # if current line starts with ----
        print(lines[i+1])  # print next line.
        print(lines[i+2])  # print line following next line.

# I need this line
# I need this line also                                      

You can store the index of the current line and thus get the next n lines: 您可以存储当前行的索引,从而获得下面的n行:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
Again few lines i do not want
"""
lines = a.split("\n")
for index, line in enumerate(lines):
    if line.startswith("----"):
        print lines[index+1]
        print lines[index+2]

You may want to check for IndexError s though. 您可能想检查IndexError s。

Plain way (almost C): 平原(几乎是C):

>>> a = """
Some lines I do not want
----- -------- --
I need this line
I need this line also
Again few lines i do not want
No nee
---- ------- --
Need this
And this
But Not this
"""

>>> start_printing, lines_printed = False, 0
>>> for line in a.split('\n'):
        if line.startswith('----'):
            start_printing = True
        elif start_printing:
            print line
            lines_printed += 1
        if lines_printed>=2:
            start_printing=False
            lines_printed = 0


I need this line
I need this line also
Need this
And this

Here something with list comprehensions: 这里有列表推导的东西:

    a = """
    Some lines I do not want 
    ----- -------- --
    I need this line
    I need this line also
    -----------------------
    A line after (---)
    A consecutive line after (---)
    """

   lines = a.split("\n")
   test = [print(lines[index+1] + '\n' + lines[index+2]) for index in range(len(lines)) if lines[index].startswith("----")]

 #Output:I need this line
         #I need this line also
         #A line after (---)
         #A consecutive line after (---)

I bumped into IndexError on further testing with more sentences, so I added an exception block: 我用更多的句子进一步测试时碰到了IndexError ,所以我添加了一个异常块:

a = """
Some lines I do not want 
----- -------- --
I need this line
I need this line also
-----------------------
A line after (---)
A consecutive line after (---)
-------------------------
Just for fun
Another one
-------------------------
"""
lines = a.split("\n")
try:
    test = [print(lines[index+1] + '\n' + lines[index+2]) for index in range(len(lines)) if lines[index].startswith("----")]
except:
    pass

Now, the desired output without exceptions: 现在,所需的输出没有例外:

I need this line
I need this line also
A line after (---)
A consecutive line after (---)
Just for fun
Another one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python搜索字符串并打印下一行x行 - Python search for a string and print the next x number of lines 在两个单独的文件中搜索字符串并使用 python3 仅打印匹配行的函数 - function to search for a string in two separate files and print only the matching lines using python3 Python:在击中字符串时从文本文件中打印下一行x行 - Python: Print next x lines from text file when hitting string 打印从字符串1到字符串2的后x行 - Print next x lines from string1 until string2 搜索开始字符串和搜索结束字符串,然后在python中打印开始到结束行之间的所有行 - search begin string and search end string then print all lines between begin to end lines in python 从python输出的变量中输出最后一行 - print last line from the variable output in python Python 从某个资源打印 terraform output 中的某些行 - Python print certain lines from terraform output from certain resource 使用 Python3 在文件中搜索字符串,将下一行的结果添加到数组中,然后在下一个字符串处停止 - Using Python3 to search a file for a string, add the results on the next lines to an array before stopping at the next string 从 web 中搜索文本并将接下来的 4 行转换为 python dataframe - Search text from web scrape and transform next 4 lines into a python dataframe Python打印输出到变量 - Python print output to variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM