简体   繁体   English

如何使 re.finditer 只返回每行一次

[英]How do I make re.finditer only return each line once

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.我正在搜索一个文本文件,它是一个“phoneBook”的分配,并且正在使用正则表达式查找器,但如果一个名称中有两次字母 a,它会打印该行两次,这是我试图避免的。 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因此,当我搜索“a”时,它会返回

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所以我希望它每一个都返回一次,并找到“a”的大写,比如 Abby

Don't use findall() .不要使用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.实际上,我不确定您为什么要使用re Do your users really enter regular expression patterns?您的用户是否真的输入了正则表达式模式? If they're just entering a plain string, use if d in line:如果他们只是输入一个纯字符串,请使用if d in line:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM