【发布时间】:2021-07-18 17:06:23
【问题描述】:
我写了一个python代码想要读取一个文本文件,用户可以输入单词,它会从文本文件中打印出想要的单词。
文本文件示例如下:
u:you
ttyl:talk to you later
l8:late
brb:be right back
lol:laughing out loud
bbl:be back later
tldr:too long; didn't read
rofl:rolling on floor laughing
gtg:got to go
这是我目前的代码:
dictionary = {}
file = open('abbreviations.txt', 'r')
lines = file.readlines()
count = 1
for line in lines:
data = line.split(":")
dictionary[data[0]] = data[1]
print("Line{}: {}".format(count, line.strip()))
count += 1
word = input("Please enter an abbreviations: ")
if dictionary.has_key(word):
print(dictionary[word])
else:
print(word)
当我运行它时,它在第 12 行显示如下错误:
AttributeError: 'dict' object has no attribute 'has_key'
这是我想要的输出:
Please enter an abbreviations: u gtg
output: u got to go
【问题讨论】:
标签: python