簡體   English   中英

python打印匹配的字符串,第n行的另一個字符串再次開始查找字符串的循環

[英]python print matched string, another string at nth line again starting the loop for finding string

我剛剛開始學習python編程。 下面是輸出文件。

SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2
  1. 我正在逐行閱讀。 首先它將搜索“服務器*”並打印
  2. 然后在SERVER中,另一個循環將開始搜索另一個字符串text3並打印和循環中斷。
  3. 然后,第一個循環將再次搜索與SERVER *相匹配的另一個單詞,依此類推。

我要求輸出為:

SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3

下面是我准備的代碼

import re
f = open('dsp.txt', 'r')
for i, line in enumerate(f.readlines()):
    line=line.rstrip('\n')
    line=line.strip()
    print(i, line)
    if line.startswith("SERVER"):
        while i > 0:
            i=i+1
            print i
            if "text3" in line: # here i am not able to increment line.
                x= line[i]
                print ("%d" % line + /n + x)
                break

為此,您不需要兩個for循環。 您只需要在找到一個search term時就對其進行更改。 像這樣:

look = 'SERVER'
tooglelook = lambda x: 'SERVER' if x == 'text3' else 'text3'
for i, line in enumerate(f.readlines()):
    if look in line:
        print line
        look = tooglelook(look)

對於給定的樣本輸入:

SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2

產生這個輸出

SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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