我有以下代码:
def search_for_person(name):
with open("address.txt", "r") as book:
records = re.split("[-]+", book.read(), re.M)
for data in records:
record = get_record(data)
if record['Name'] == name:
print record
def get_record(string):
return dict(re.findall("^(.*): (.*)$", string, re.M))
当我使用它来尝试定位记录时,我得到以下输出:
Enter name: Daniel Ghi
{'Home Phone No.': 'Example', 'Mobile Phone No.': 'Example', 'Name': 'Daniel Ghi
', 'Address': 'Example'}
Traceback (most recent call last):
File "address.py", line 35, in <module>
search_for_person(name)
File "address.py", line 18, in search_for_person
if record['Name'] == name:
KeyError: 'Name'
如您所见,这确实打印出正确的数据,但它仍然出现 KeyError,我不知道为什么。任何人都可以启发我吗?