You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python通讯录代码中实现联系人的精准删除?

通讯录精准删除问题修复

问题根源

原代码的删除逻辑使用if name not in line:判断,只要行文本中包含输入的姓名片段就会被过滤删除。比如当通讯录里有"J"和"James"两个联系人时,删除"J"会同时删掉包含"J"的"James"条目,无法实现精准匹配。

修复思路

由于联系人条目格式固定为姓名 : 电话号码,我们可以通过拆分每行内容提取出完整的联系人姓名,再与要删除的姓名做精确相等比对,只过滤掉姓名完全匹配的条目。

关键代码修改

修正后的删除模块

elif q == '4':
    target_name = input('Enter name to delete from contact book: ')
    print('\n')
    with open("contact.txt", "r+") as f:
        lines = f.readlines()
        f.seek(0)
        for line in lines:
            # 去除换行符与前后空白,跳过空行
            cleaned_line = line.strip()
            if not cleaned_line:
                continue
            # 按固定分隔符拆分,只拆分一次避免电话号码含冒号出错
            contact_name, _ = cleaned_line.split(' : ', 1)
            # 仅当姓名完全不匹配时,保留该行
            if contact_name != target_name:
                f.write(cleaned_line + '\n')
        f.truncate()

额外优化:修复搜索模块的逻辑漏洞

原搜索模块会在第一行不匹配时直接终止循环,漏掉后续可能的匹配项,同步修复如下:

elif q == '2':
    with open('contact.txt', 'r') as f:
        search_key = input('Search: ')
        found = False
        for line in f:
            cleaned_line = line.strip()
            if not cleaned_line:
                continue
            contact_name, phone = cleaned_line.split(' : ', 1)
            # 支持姓名或电话模糊搜索
            if search_key in contact_name or search_key in phone:
                print(f"{contact_name} : {phone}\n")
                found = True
        if not found:
            print('Contact not found \n')

完整修正代码

while True:
    q = input('Press 1 to add, 2 to search, 3 to display, 4 to delete, 5 to clear contact book and 6 to quit: ')
    if q == '1':
        with open('contact.txt', 'a') as f:
            name = input('Name: ')
            phone= input('Phone: ')
            f.writelines((name, ' : ', phone, '\n'))
            print('\n')

    elif q == '2':
        with open('contact.txt', 'r') as f:
            search_key = input('Search: ')
            found = False
            for line in f:
                cleaned_line = line.strip()
                if not cleaned_line:
                    continue
                contact_name, phone = cleaned_line.split(' : ', 1)
                if search_key in contact_name or search_key in phone:
                    print(f"{contact_name} : {phone}\n")
                    found = True
            if not found:
                print('Contact not found \n')

    elif q == '3':
        with open('contact.txt', 'r') as f:
            print('The current entries in the contact book are \n')
            for line in f:
                print(line, end='')
            print('\n')

    elif q == '4':
        target_name = input('Enter name to delete from contact book: ')
        print('\n')
        with open("contact.txt", "r+") as f:
            lines = f.readlines()
            f.seek(0)
            for line in lines:
                cleaned_line = line.strip()
                if not cleaned_line:
                    continue
                contact_name, _ = cleaned_line.split(' : ', 1)
                if contact_name != target_name:
                    f.write(cleaned_line + '\n')
            f.truncate()

    elif q == '5':
        with open('contact.txt', 'w+') as f:
            f.truncate()
                
    else:
        break

内容的提问来源于stack exchange,提问作者zeitgeist_7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 16:05:25