我需要创建一个类,该类从文件“ cars.txt”中读取数据。数据的每一行都存储到数据库中,直到到达文件中的停止点为止。搜索数据库也是如此,搜索从搜索到的文件中告知每辆汽车的信息,如果不在数据库中,则会打印:“在数据库中找不到此车辆”,否则将打印索引,其中该信息在数据库中找到。这是我从中读取数据的文件:
Chevrolet 2003 12000.0
Lincoln 2007 32000.0
Lexus 2005 23678.0
Ford 2001 14000.0
Hyundai 2008 21000.0
Honda 2004 15500.0
EndDatabase
Lexus 2005 23678.0
Ford 2001 7595.0
Honda 2004 15500.0
Ford 2001 14000.0
EndSearchKeys
我尝试使用 init (self), eq (self)函数来读取和存储数据以及__str __(self)函数来设置班级数据以正确的格式显示,但是我可以像通常读取文件那样获取要读取和打印的文件,但无法以正确的格式获取它。我的代码中的“数据库”功能显示文件正在正确读取。这是我到目前为止的内容:
class Car:
def __init__(self,m,y,p):
self._make=m
self._year=y
self._price=p
def getMake(self):
return self._make
def getYear(self):
return self._year
def getPrice(self):
return self._price
def setMake(self,m):
self._make=m
def setYear(self,y):
self._year=y
def setPrice(self,p):
self._price=p
def __eq__(self, other):
result=self._make==other._make and self._year==other._year and self._price==other._price
return result
def __str__(self):
result=("Description of car:+"+"\n\tMake:"+self._make+"\n\tYear:"+self._year+"\n\tPrice:"+self._price)
return result
def database():
f=open("cars.txt","r")
stop1='EndDatabase'
stop2='EndSearchKeys'
while f!=stop1:
data=f.readline().rstrip("\n")
if data==stop1:
break
else:
print(data,"This ends data.")
while f!=stop2:
search=f.readline().rstrip("\n")
if search==stop2:
break
else:
print(search)
database()
我的输出与我已经完成的当前代码一起,按原样打印文件,直到第一个停止点为止,并与文件的第二部分相同。我希望输出看起来像这样:
Description of car:
Make : Chevrolet
Year : 2003
Price: $12000.00
Description of car:
Make : Lincoln
Year : 2007
Price: $32000.00
Description of car:
Make : Lexus
Year : 2005
Price: $23678.00
Description of car:
Make : Ford
Year : 2001
Price: $14000.00
Description of car:
Make : Hyundai
Year : 2008
Price: $21000.00
Description of car:
Make : Honda
Year : 2004
Price: $15500.00
Search key =
Description of car:
Make : Lexus
Year : 2005
Price: $23678.00
This vehicle was found at index = 2.
Search key =
Description of car:
Make : Ford
Year : 2001
Price: $7595.00
This vehicle was not found in the database.
Search key =
Description of car:
Make : Honda
Year : 2004
Price: $15500.00
This vehicle was found at index = 5.
Search key =
Description of car:
Make : Ford
Year : 2001
Price: $14000.00
This vehicle was found at index = 3.