Python读取缩写词典文件查词时has_key报错及多词查询如何实现?
问题解决方案
错误原因
dict.has_key()是Python 2专属语法,Python 3已经彻底移除该方法,因此会抛出属性不存在的报错。Python 3中判断键是否存在于字典的标准写法是key in dict。
功能实现修改点
- 优化文件读取逻辑:使用
with上下文管理器自动管理文件句柄,避免文件资源泄漏 - 读取每行时提前去除首尾空白字符,避免释义末尾附带换行符
- 将用户输入按空格切割为列表,遍历每个缩写查询字典,未匹配到则保留原词,最后拼接为完整字符串输出
完整修改后代码
dictionary = {} # 用with上下文管理器自动关闭文件 with open('abbreviations.txt', 'r', encoding='utf-8') as file: lines = file.readlines() count = 1 for line in lines: line = line.strip() if not line: # 跳过空行 continue data = line.split(":") # 提前去除首尾空白,避免释义带多余字符 dictionary[data[0].strip()] = data[1].strip() print("Line{}: {}".format(count, line)) count += 1 words = input("Please enter an abbreviations: ").strip().split() result = [] for word in words: # 用in代替has_key判断键是否存在 if word in dictionary: result.append(dictionary[word]) else: result.append(word) # 拼接结果输出 print(' '.join(result))
内容的提问来源于stack exchange,提问作者OMG C
相关产品推荐
相关产品推荐

