簡體   English   中英

Python不在第一行以外的任何行上找到詞組嗎?

[英]Python Not finding phrase on any line other than first?

我正在嘗試制作一個python聯系人管理器,並且我做了一個搜索contacts.txt文件的函數。 它可以成功找到“您”,或列表中第一個應為您的聯系人,但找不到其他人。 我不知道為什么或如何發生。

功能

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])

                self.managerMenu()

            else:
                print("Contact not found.")
                self.managerMenu()

contacts.txt

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

當我運行該文件,打字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

但是當我與DAD聯系人進行相同的操作時:

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()

請注意,我將else移到了與for循環相同的縮進級別,這使其成為for..else構造, else塊僅在不使用break來打破循環的情況下才執行,這意味着我們沒有查找任何匹配的行。

同樣讀取文件兩次將非常低效,您可以改用iter()為文件創建一個迭代器。 范例-

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。

對於正則表達式來說,這聽起來似乎更好。 考慮以下示例。

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

暫無
暫無

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

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