Skip to main content
 首页 » 编程设计

匹配后python搜索键和读取行并发送到列表

2024年10月01日7虾米哥

我有如下的文件输出

some junk text 
ignore above text 
pen: 4 
apple: 10 
orange: 20 
pen: 30 
apple: 40 
bat: 20 
ball: 300 
football: 500 
pencil: 200 
again junk test ignore it 

要求:

在文件中搜索关键字并将接下来的 10 行输出作为值发送到 list1

我试过下面的代码但没有用。需要您的帮助才能取得成果。

from itertools import islice 
list1 = [] 
with open ("file.txt") as fin: 
    for line in fin: 
        if line.startswith("ignore above text"): 
            list1 = (islice(fin,9)) 
            print list1 

预期输出:

 list1 = ['pen: 4','apple: 10','orange: 20',pen: 30','apple: 40','bat: 20','ball: 300', 'football: 500', 'pencil'] 

请您参考如下方法:

您需要将其转换为列表(或元组):

list1 = list((islice(fin,9))) 
#         ^ 

否则它只是一个生成器,如果被问到,它会为您提供下一个值。但是,您不妨坚持使用生成器并在之后对其进行迭代:

for item in list1: 
    print(item.strip()) 
    # or anything else 

所以你的代码可能会变成:

from itertools import islice 
with open("test.txt") as fp: 
    for line in fp: 
        if line.startswith('ignore above text'): 
            for item in islice(fp, 9): 
                print(item.strip()) 

生成器是 Python 中一种非常有用且经常使用的机制,您可能需要 read sth. about them here .