Home > OS >  How do I make re.finditer only return each line once
How do I make re.finditer only return each line once

Time:12-09

I am searching a text file that is a "phoneBook" for an assignment and am using regex finditer, but if a name has the letter a in it twice it prints that line twice which is what I am trying to avoid. Also is there a way to have it ignore case?

def searchPhonebook(s): #This will search the phonebook(s) for the inputed data that is assigned to d
    print()
    d=input("Please enter the Name, Character, Phone Number, or a number: ") #Variable d which is the inputted data
    print()
    import re
    pattern = re.compile(d)
    for line in open("phone.txt"):
        for match in re.finditer(pattern,line):
            print(line)

So when I search 'a' it returns

Jack Hammer,277-4829
Jack Hammer,277-4829
Mike Rafone,345-3453
Earl Lee Riser,701-304-8293

So I would like it to return each one once, and also find capitalization of 'a', like Abby

CodePudding user response:

Don't use findall(). Just test whether the line matches the pattern:

for line in open("phone.txt"):
    if re.search(pattern, line):
        print(line)

Actually, I'm not sure why you're using re at all. Do your users really enter regular expression patterns? If they're just entering a plain string, use if d in line:

  • Related