简体   繁体   English

在 python 中的特定字符串之后搜索文本文件中的字符串

[英]search a string in a text file after a particular string in python

Suppose this is the text file which has 10 line content.假设这是一个有 10 行内容的文本文件。

1 mpe:p01 
2 mpe:p02 
3 * xyz 3 
4 mpe:p04 
5 mpe:p05 
6 mpe:p06 
7 mpe:p07 
8 mpe:p08 
9 mpe:p09 
10 mpe:p100 

I need to search string "mpe:" after "xyz" string.我需要在“xyz”字符串之后搜索字符串“mpe:”。

My piece of code is:我的一段代码是:

str1_name ="* xyz"  
str2_name = "mpe:" ` 

lines = [] 

with open("textfile.txt",'r') as f:
   for line in f:
       if str2_name in line:
           lines.append(line)  
        lines2=lines[0]  
    print(lines2)

it is giving me output:它给了我 output:

1 mpe:p0 1 mpe:p0

but I want the output:但我想要 output:

4 mpe:p0 4 mpe:p0

You need to check if you encountered string xyz first.您需要先检查是否遇到字符串xyz If you did, then set a flag to true.如果你这样做了,那么设置一个标志为真。 Then continue reading file.然后继续读取文件。 If previous line read was xyz , the flag would have been set to True .如果上一行读取的是xyz ,则该标志将设置为True Check if current line has mpe and append that line to lines .检查当前行是否有mpe和 append 该行到lines See if this code works.看看这段代码是否有效。

str1_name ="* xyz"  
str2_name = "mpe:" 
prev_xyz = False

lines = [] 

with open("textfile.txt",'r') as f:
    for line in f:
       if str2_name in line and prev_xyz:
           lines.append(line.strip())  
           #lines2=lines[0] prev line will strip out \n
       if str1_name in line:
           prev_xyz = True
       else:
           prev_xyz = False
print(lines2)

Output: Output:

['4 mpe:p04']
lines = []
line_after_str1=[]

str1_name ="* xyz"

str2_name = "mpe:" 

with open("textfile.txt",'r') as f:
    all_lines=f.readlines()
    for line in range(len(all_lines)):
        
        if str1_name in all_lines[line]:
            line_after_str1.append(all_lines[line+1].replace('\n',''))
        elif str2_name in all_lines[line]:
            lines.append(all_lines[line].replace('\n',''))
        

print(line_after_str1)

Output: Output:

['4 mpe:p04']

Well, if you're sure mpe follows xyz , you could run something like:好吧,如果你确定mpe遵循xyz ,你可以运行类似:

str1_name ="* xyz"  

with open("textfile.txt",'r') as f:
    for line in f:
        while str1_name not in line:
            pass
        if str2_name in line:
            print(next(f))

If the searched string doesn't follow immediately:如果搜索到的字符串没有立即出现:

str1_name ="* xyz"
str2_name = "mpe:"  

checkpoint = False

with open("textfile.txt",'r') as f:
    for line in f:
        if str1_name in line:
            checkpoint = True
        if checkpoint and str2_name in line:
            print(line)
            break

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM