簡體   English   中英

匹配后python搜索鍵和讀取行並發送到列表

[英]python search key and read line after matching and send to list

我有如下文件輸出

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中一種非常有用且經常使用的機制,您可能想閱讀某事。 關於他們在這里

你可以試試下面的代碼:

file_with_data = open("file.txt", "r")
raw_data = file_with_data.read()
file_with_data.close()

input_data_as_list = raw_data.split("\n")
output_data = []
for i in range(len(input_data_as_list)):
    if input_data_as_list[i] == "ignore above text":
        output_data = input_data_as_list[i+1:i+10]
        break

print(output_data)
 mystr=open("your\\file\\path").read()
 my_list=mystr.split("\n")
 my_list=[item for item in my_list if not item.startswith("ignore")]

暫無
暫無

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

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