在python中搜索文本文件中特定字符串后的字符串[已关闭]

5gfr0r5j  于 2023-01-01  发布在  Python
关注(0)|答案(3)|浏览(153)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
昨天关门了。
Improve this question
假设这是一个10行内容的文本文件。
我需要在“xyz”字符串后搜索字符串“mpe:“。
我的代码是:

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)

它会给出输出:
1兆像素:p0
但我想要输出结果
4兆像素:p0

nnvyjq4y

nnvyjq4y1#

你需要先检查你是否遇到了字符串xyz。如果你遇到了,那么设置一个标志为true。然后继续读取文件。如果读取的前一行是xyz,那么标志将被设置为True。检查当前行是否有mpe,并将该行附加到lines。看看这段代码是否有效。

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(lines)

输出:

['4 mpe:p04']
mftmpeh8

mftmpeh82#

好吧,如果你确定 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))

如果搜索的字符串没有紧跟在后面:

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
iqxoj9l9

iqxoj9l93#

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)

输出:

['4 mpe:p04']

相关问题