Python除了第一行之外,在任何一行都找不到短语?

Python除了第一行之外,在任何一行都找不到短语?,python,Python,我正在尝试制作一个python联系人管理器,并制作了一个函数,用于搜索contacts.txt文件。它可以成功地找到“你”,或者名单上的第一个联系人应该是你,但是它找不到其他人。我不知道这是为什么或如何发生的 功能 contacts.txt 当我运行文件时,键入readfile,然后you生成以下内容: Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit() readfile Type

我正在尝试制作一个python联系人管理器,并制作了一个函数,用于搜索
contacts.txt
文件。它可以成功地找到“你”,或者名单上的第一个联系人应该是你,但是它找不到其他人。我不知道这是为什么或如何发生的

功能 contacts.txt 当我运行文件时,键入
readfile
,然后
you
生成以下内容:

Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
you
Contact: YOU

    First Name: FELIX

    Last Name: MARTIN

    Number: (555)-555-5555

    Address: 123 Sesame Street
但是当我对爸爸做同样的事情时,请联系:

Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
dad
Contact not found.

我正在c9.io上运行Python 3.4。如果有任何帮助,我们将不胜感激。

问题在于每行您都要检查
lookup.upper()
是否在该行中,如果在该行中,则打印该行,如果不在该行中,则调用
self.managerMenu()
,我想它会打印出您程序中的菜单

无论如何,您都要调用
self.managerMenu()
,因此您应该在完全浏览完文件后才调用它。范例-

def readFile(self):

    f = open('contacts.txt', 'r')
    lines = f.readlines()
    cmd = str(input("Type in a contact REFERENCE name.\n"))
    lookup = cmd

    with open('contacts.txt') as myFile:
        for num, line in enumerate(myFile, 1):
            if lookup.upper() in line:

                print(lines[num - 1])
                print(lines[num])
                print(lines[num + 1])
                print(lines[num + 2])
                print(lines[num + 3])
                break
        else:
            print("Contact not found.")
    self.managerMenu()
def readFile(self):

    lookup = input("Type in a contact REFERENCE name.\n")

    with open('contacts.txt') as myFile:
        my_file_iter = iter(myFile)
        for num, line in enumerate(my_file_iter, 1):
            if lookup.upper() in line:

                print(line)
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                break
        else:
            print("Contact not found.")
    self.managerMenu()
请注意,我将
else
移动到了与
for
循环相同的缩进级别,这使它成为一个
for..else
构造,只有在我们不使用
break
来中断循环时,
else
块才会执行,这意味着我们没有找到任何匹配的行

另外,读取文件两次将非常低效,您可以使用
iter()
为文件创建迭代器。范例-

def readFile(self):

    f = open('contacts.txt', 'r')
    lines = f.readlines()
    cmd = str(input("Type in a contact REFERENCE name.\n"))
    lookup = cmd

    with open('contacts.txt') as myFile:
        for num, line in enumerate(myFile, 1):
            if lookup.upper() in line:

                print(lines[num - 1])
                print(lines[num])
                print(lines[num + 1])
                print(lines[num + 2])
                print(lines[num + 3])
                break
        else:
            print("Contact not found.")
    self.managerMenu()
def readFile(self):

    lookup = input("Type in a contact REFERENCE name.\n")

    with open('contacts.txt') as myFile:
        my_file_iter = iter(myFile)
        for num, line in enumerate(my_file_iter, 1):
            if lookup.upper() in line:

                print(line)
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                print(next(my_file_iter))
                break
        else:
            print("Contact not found.")
    self.managerMenu()

请注意,如果
self.managerMenu()
真的是要打印的菜单,您可以再次进入这个
readFile(self)
方法,那么这将是一种不好的菜单方式,因为在运行程序一段时间后,您的堆栈将很大(因为您使用的是菜单递归),退出也会很复杂。我建议您改用
while
循环。

如果看不到任何会导致您描述的行为的因素,我也会在if语句中使用line.upper(),这样您就完全可以确定它会忽略两边的大写字母。以防万一,contacts.txt可能是DaD或DaD而不是DaD。

对于正则表达式来说,这似乎是一个更好的工作。考虑下面的例子。

import re
contacts_text = """Contact: YOU
    First Name: FELIX
    Last Name: MARTIN
    Number: (555)-555-5555
    Address: 123 SESAME STREET
Contact: DAD
    First Name: JOHN
    Last Name: SMITH
    Number: (555)-555-5555
    Address: 123 SESAME STREET"""
parsed_contacts = re.compile(r'(?i)(\s*contact\s*:?\s*)(\w*)(.*?)(?=contact|$)', flags=re.DOTALL).findall(contacts_text)
contacts = {}
search_fields = {'First Name': r'(?i)(\s*first\s*name\s*:?\s*)(.*?)(\n)',
                 'Last Name': r'(?i)(\s*last\s*name\s*:?\s*)(.*?)(\n)',
                 'Number': r'(?i)(\s*number\s*:?\s*)(.*?)(\n)',
                 'Address': r'(?i)(\s*address\s*:?\s*)(.*?)(\n)'}

for pc in parsed_contacts:
    contact_header = pc[1]
    contacts[contact_header] = {}
    for seach_id, regex in search_fields.items():
        match_obj = re.search(regex, pc[2])
        if match_obj:
            contacts[contact_header][seach_id] = match_obj.group(2)
        else:
            contacts[contact_header][seach_id] = None
print contacts

什么是self.managerMenu()?为什么要读取文件两次?您要么阅读所有行并使用该列表,要么一次使用一行(最好)注释掉
self.managerMenu()
-我打赌它会干扰您的循环。代码是我正在制作的程序的摘录。self.managerMenu()与此无关。xP