Python: How to search for a string and print while next different string shows up repeadtedly

Viewed 38

Need a little help here. I have a file which is something like below:

category: dog1
member10
member20
category: cat
member1
member2
member3
category: mydog
member100
member200
member300
category: lion
member1000
member2000
member3000
member4000
category: wolf
member4
member5
member6
category: dog4
member400
member500
member600
member700
member800

I am trying to pull the details of all the categries that have "dog" in its name along with its respective members, preferably in a dictionary, so that I can iterate on it for further checks.

Tried many ways like putting up a flag for printing within 'if' loop but still not able to get the correct code.

===========================================


import re
from re import search
keyword = "dog"

should_print = False
file = open("inputfile.txt","r")
lines = file.readlines()
for line in lines:
    if (should_print or keyword in line):
        print (line.strip("\n"))
        should_print = True

===========================================

Above starts with category having "dog" which I want, but then keep printing till the end of file. Not sure where exactly we need to set the 'should_print' flag False and then may be a 'continue' statement.

It would be great if someone can guide or redirect with similar or a different approach.

Thanks in advance.

3 Answers

You are almost there, but you need to set should_print to false each loop, IF the line is a category marker.

keyword = "dog"

should_print = False
file = open("inputfile.txt","r")
lines = file.readlines()
for line in lines:
    if line.startswith('category'):
        should_print = False
    if (should_print or keyword in line):
        print (line.strip("\n"))
        should_print = True

Output:

category: dog1
member10
member20
category: mydog
member100
member200
member300
category: dog4
member400
member500
member600
member700
member800

try below code:

keyword = "dog"

should_print = False
file = open("inputfile.txt","r")
lines = file.readlines()
for line in lines:
    if "category" in line:
        if keyword in line:
            should_print = True
        else:
            should_print = False
    if should_print:
        print(line.strip())

I'd suggest you first read all and stores into a dict, then use it. defaultdict can help to do it (not mandatory)

from collections import defaultdict

key_name = ""
result = defaultdict(list)
with open("test.txt") as file:
    for line in file:
        if 'category:' in line:
            key_name = line.split(":")[1].strip()
        else:
            result[key_name].append(line.rstrip())

# result is like
{'dog1': ['member10', 'member20'], 'cat': ['member1', 'member2', 'member3'], 'mydog': ['member100', 'member200', 'member300'], ...}

Use

keyword = "dog"
for k, values in result.items():
    if keyword in k:
        print(k, values)
Related