如果找到另一个字符串,则在字符串之间打印行

时间:2018-11-28 13:38:29

标签: python string python-3.x substring

我有一个带代码块的文本文档,用$分隔。 现在,如果在$之间找到了某个字符串,我想打印出$之间的每一行。我搜索的字符串并不总是在同一位置。 我想遍历整个文档,直到打印出所有块。 我已经尝试过其他方法,但没有成功。

文档如下:

$    
aa   
string    
$
aa   
bb  
cc  
$
aa  
bb
string  
cc  
$

输出应为:

$    
aa   
string    
$
aa  
bb
string  
cc  
$

上次尝试代码:

def usefullInfo():
    data_list = []
    with open ("file.txt") as f:
        data = f.read()
        marker, pos = "string", 0
        while data.find(marker) != -1:
            pos = data.find(marker)
            start = data.find ("$", pos)
            stop = data.find ("$", pos)
            data_list.append(data[start:stop])
            data = data[stop+1:]
    print (data_list)

3 个答案:

答案 0 :(得分:0)

每次遇到“ $”时,切换写入变量

def usefullInfo():
    write = False
    with open ("file.txt") as f:
        for line in f:
            if '$' in line:
                write = not write
            if write:
                print (line)
        print("$")

usefullInfo()

这是你想要的吗?

答案 1 :(得分:0)

尝试:

with open('data.txt', 'r') as F:
    lines = F.readlines()

search_string = 'string'
long_line     = ''.join([x.replace(' ','') for x in lines])
blocks        = [x.lstrip() for x in long_line.split('$')]

for block in blocks:
    if not(block=='' or block=='\n') and search_string in block.split('\n'):
        print('$\n'+block+'$')

输出:

$
aa
string
$
$
aa
bb
string
cc
$

答案 2 :(得分:0)

将输入字符串存储在队列中。 如果找到搜索字符串,则设置write = True。 只要输入中遇到$,只要将write变量设置为True,就从队列中删除所有项目,并打印这些项目。

from queue import Queue

f = open('input.txt', 'r')
q = Queue()
write = False

for i in f:
    i = i.strip() # to remove newline at the end
    if i == '$':
        if write:
            # empty the queue and also print the items
            while not q.empty():
                print(q.get())
        else:
            # empty the queue
            while not q.empty():
                q.get()
        write = False
    elif i == 'string': # search string is found
        write = True
    q.put(i)

print('$')