Dictionary 在Python3中读取文件并将信息积累到字典中
我已经在这方面工作了几天,但我无法让它工作。我试图阅读一个文件,并将一些信息积累到三本不同的字典中。这是存档在线课程的作业,解决方案未发布 下面是要读取的文件:它从下面开始Dictionary 在Python3中读取文件并将信息积累到字典中,dictionary,Dictionary,我已经在这方面工作了几天,但我无法让它工作。我试图阅读一个文件,并将一些信息积累到三本不同的字典中。这是存档在线课程的作业,解决方案未发布 下面是要读取的文件:它从下面开始 Restaurant name to rating: # dict of {str: int} {'Georgie Porgie': 87%, 'Queen St. Cafe': 82%, 'Dumplings R Us': 71%, 'Mexican Grill': 85%, 'Deep Fried Everything'
Restaurant name to rating:
# dict of {str: int}
{'Georgie Porgie': 87%,
'Queen St. Cafe': 82%,
'Dumplings R Us': 71%,
'Mexican Grill': 85%,
'Deep Fried Everything': 52%}
Price to list of restaurant names:
# dict of {str, list of str}
{'$': ['Queen St. Cafe', 'Dumplings R Us', 'Deep Fried Everything'],
'$$': ['Mexican Grill'],
'$$$': ['Georgie Porgie'],
'$$$$': []}
Cuisine to list of restaurant names:
# dict of {str, list of str}
{'Canadian': ['Georgie Porgie'],
'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
'Malaysian': ['Queen St. Cafe'],
'Thai': ['Queen St. Cafe'],
'Chinese': ['Dumplings R Us'],
'Mexican': ['Mexican Grill'] (--->Ends here, this part is not included).
以下是我正在使用的代码:
def read_restaurants(file):
""" (file) -> (dict, dict, dict)
Return a tuple of three dictionaries based on the information in the file:
- a dict of {restaurant name: rating%}
- a dict of {price: list of restaurant names}
- a dict of {cusine: list of restaurant names}
"""
# Initiate dictionaries
name_to_rating = {}
price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []}
cuisine_to_names = {}
# Open the file
with open('restaurant_file_above.txt','r') as file:
# Build line list
lines = file.read().splitlines()
# Process the file
for i in range(0,len(lines),5):
# Read individual data
name = lines[i]
rating = int(lines[i+1].strip('%')) #error occurs here
price = lines[i+2]
cuisines = lines[i+3].split( ',' )
# Assign rating to name
name_to_rating[name]=rating;
# Assign names to price
price_to_names[price].append(name)
# Assign names to cuisine
for cuisine in cuisines:
cuisine_to_names.setdefault(cuisine,[]).append(name)
return name_to_rating, price_to_names, cuisine_to_names
我是初学者,所以非常感谢您的指导。我只是不知道还能尝试什么。顺便说一下,我使用的是Python 3.4.2。您试图读取的文件是最终输出,而不是原始输出。下面是一个在docstring中包含原始数据的解决方案
def read_restaurants(filename):
""" (file) -> (dict,dict,dict)
Return a tuple of three dictionaries based on the information in the file below
Georgie Porgie
87%
$$$
Canadian, Pub Food
Queen St. Cafe
82%
$
Malaysian, Thai
Dumplings R Us
71%
$
Chinese
Mexican Grill
85%
$$
Mexian
Deep Fried Everything
52%
$
Pub Food
- a dict of {restaurant name: rating}
- a dict of {price: list of restaurant names}
- a dict of {cusine: list of restaurant names}
"""
name_to_rating = {}
price_to_names = {'$':[],'$$':[],'$$$':[],'$$$$':[]}
cuisine_to_names = {}
#set incrementing number
i = 1
with open(filename,'rU') as f:
for line in f:
#check if blank line
if line.strip():
line = line.strip('\n')
#determine restaurant_name
if i == 1:
restaurant_name = line
#create dictionaries with restaurant_name
if i == 2:
rating = line
name_to_rating[restaurant_name] = rating
elif i == 3:
price = line
price_to_names[price].append(restaurant_name)
elif i == 4:
#could be multiple cuisines for each restaurant_name
cuisine_list = line.split(',')
for cuisine in cuisine_list:
cuisine_to_names[cuisine] = restaurant_name
#at blank line start increment over
else:
i = 0
i += 1
print name_to_rating
print price_to_names
print cuisine_to_names
return (name_to_rating,price_to_names,cuisine_to_names)
def main():
return read_restaurants('restaurants.txt')
if __name__ == "__main__":
main()
我认为上述答案并不能正确地保存菜名词典。请参阅下面的代码。这项工作:
def read_restuarants(file):
name_to_rating={}
price_to_names={'$':[],'$$':[],'$$$':[], '$$$$':[]}
cuisine_to_names={}
i=1
with open(file) as f:
contents = f.readlines()
for line in contents:
if line.strip():
l = line.strip()
if i ==1:
rest_name = l
if i ==2:
rating=l
name_to_rating[rest_name]=rating
if i==3:
price=l
price_to_names[l].append(rest_name)
if i==4:
cuisine_list = l.split(',')
for cuisine in cuisine_list:
if cuisine not in cuisine_to_names.keys():
cuisine_to_names[cuisine] = [rest_name]
else:
cuisine_to_names[cuisine].append(rest_name)
else:
i=0
i=i+1
print name_to_rating
print price_to_names
print cuisine_to_names
我就是这样解决我的问题的 我将在这里分享它,因为我在网上没有找到任何解决方案 我将整个文件分解为单词,并将它们保存在“lines”变量中,并使用while循环,其中考虑到:
lines[i] = restaurant name
lines[i+1] = rating
lines[i+2] = price
lines[i+3] = cuisine
lines[i+4] = blank
所以我处理了上面的数据,在while循环结束时,我只是将“I”增加5
以下是全部内容,包括read_餐厅:
# The file containing the restaurant data.
FILENAME = 'restaurants_small.txt'
def recommend(file, price, cuisines_list):
"""(file open for reading, str, list of str) -> list of [int, str] list
Find restaurants in file that are priced according to price and that are
tagged with any of the items in cuisines_list. Return a list of lists of
the form [rating%, restaurant name], sorted by rating%.
"""
# Read the file and build the data structures.
# - a dict of {restaurant name: rating%}
# - a dict of {price: list of restaurant names}
# - a dict of {cusine: list of restaurant names}
name_to_rating, price_to_names, cuisine_to_names = read_restaurants(file)
# Retrieves all restaurants matching specific price tag (e.g. '$') from 'price' argument
names_matching_price = price_to_names[price]
# Get restaurant names (from above price tag) that also belong to cuisine in cuisines_list
names_final = filter_by_cuisine(names_matching_price, cuisine_to_names, cuisines_list)
# Retrieve ratings from restaurants in names_final and return sorted output by ratings
result = build_rating_list(name_to_rating, names_final)
return result
def build_rating_list(name_to_rating, names_final):
""" (dict of {str: int}, list of str) -> list of list of [int, str]
Return a list of [rating%, restaurant name], sorted by rating%
>>> name_to_rating = {'Georgie Porgie': 87,
'Queen St. Cafe': 82,
'Dumplings R Us': 71,
'Mexican Grill': 85,
'Deep Fried Everything': 52}
>>> names = ['Queen St. Cafe', 'Dumplings R Us']
[[82, 'Queen St. Cafe'], [71, 'Dumplings R Us']]
"""
# For each restaurant in names_final, append corresponding rating (sorted) first to result
result = list()
for restaurant in names_final:
result.append([name_to_rating[restaurant],restaurant])
return sorted(result,reverse=True)
def filter_by_cuisine(names_matching_price, cuisine_to_names, cuisines_list):
""" (list of str, dict of {str: list of str}, list of str) -> list of str
>>> names = ['Queen St. Cafe', 'Dumplings R Us', 'Deep Fried Everything']
>>> cuis = 'Canadian': ['Georgie Porgie'],
'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'],
'Malaysian': ['Queen St. Cafe'],
'Thai': ['Queen St. Cafe'],
'Chinese': ['Dumplings R Us'],
'Mexican': ['Mexican Grill']}
>>> cuisines = ['Chinese', 'Thai']
>>> filter_by_cuisine(names, cuis, cuisines)
['Queen St. Cafe', 'Dumplings R Us']
"""
# For each cuisine we want, check if the names within price range belong to that cuisine
result = list()
# For each name that is in cuisines_list, we check if restaurant name is in there and return it
for cuisine in cuisines_list:
for name in names_matching_price:
if name in cuisine_to_names[cuisine] and name not in result:
result.append(name)
return result
def read_restaurants(file):
""" (file) -> (dict, dict, dict)
Return a tuple of three dictionaries based on the information in the file:
- a dict of {restaurant name: rating%}
- a dict of {price: list of restaurant names}
- a dict of {cusine: list of restaurant names}
"""
name_to_rating = {}
price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []}
cuisine_to_names = {}
with open(file) as f:
i = 0
# Store all lines (without \n) to lines in a list of words
lines = f.read().splitlines()
while i < len(lines):
# we know the following:
# line[i] = restaurant name, line[i+1] = rating
# line[i+2] = price, line[i+3] = cuisine
name_to_rating[lines[i]] = lines[i+1]
# match price to name
if lines[i+2] not in price_to_names.keys():
price_to_names[lines[i+2]] = [lines[i]]
else:
price_to_names[lines[i+2]].append(lines[i])
# add list of restaurants per cuisine
cuisines = lines[i+3].split(',')
for cuisine in cuisines:
if cuisine not in cuisine_to_names.keys():
cuisine_to_names[cuisine] = [lines[i]]
else:
cuisine_to_names[cuisine].append(lines[i])
# while loop is incremented by 5 as name is in position 0, rating 1, price 2, cuisine 3, blank line 4
i += 5
return name_to_rating, price_to_names, cuisine_to_names
#包含餐厅数据的文件。
FILENAME='restaurants\u small.txt'
def推荐(文件、价格、菜品清单):
“”(文件打开读取,str,str列表)->list of[int,str]列表
在文件中查找按价格定价且
已标记为菜系列表中的任何项目。返回菜系列表
表格[评级%,餐厅名称],按评级%排序。
"""
#读取文件并构建数据结构。
#-一份{餐厅名称:评级%}
#-一份{价格:餐厅名称清单}的目录
#-一份{cusine:餐厅名称列表}的口述
名称到名称、价格到名称、菜肴到名称=阅读餐厅(文件)
#从“price”参数中检索与特定价格标签(例如“$”)匹配的所有餐厅
名称匹配价格=价格匹配名称[价格]
#获取同样属于菜系列表中菜肴的餐厅名称(从上面的价格标签中)
names\u final=按菜系筛选(菜系名称、菜系价格、菜系名称、菜系列表)
#在names_final中从餐馆检索评级,并按评级返回排序后的输出
结果=建立分级列表(名称分级、名称最终)
返回结果
def构建等级列表(名称到等级,名称最终):
“”(dict of{str:int},list of str)->list of[int,str]
返回[评级%、餐厅名称]列表,按评级%排序
>>>name_to_rating={'Georgie Porgie':87,
“皇后街咖啡馆”:82,
“饺子反美”:71,
“墨西哥烤肉店”:85岁,
“油炸一切”:52}
>>>名称=['皇后街咖啡馆','饺子R Us']
[[82'皇后大道咖啡馆'],[71'饺子反斗城']]
"""
#对于names_final中的每个餐厅,首先将相应的评级(排序)附加到结果中
结果=列表()
对于最终名称中的餐厅:
结果。追加([餐厅名称到餐厅评级])
返回排序(结果,反向=真)
def按菜肴过滤(名称匹配价格、菜肴名称、菜肴列表):
“”“(str列表,dict of{str:list of str},list of str)->list of str
>>>名称=[‘皇后街咖啡馆’、‘饺子反斗城’、‘油炸一切’]
>>>cuis='加拿大人':['Georgie Porgie'],
“酒吧食品”:[“乔治·波吉”,“油炸所有东西”],
‘马来西亚人’:[‘皇后街咖啡馆’],
‘泰语’:[‘皇后街咖啡馆’],
‘中国人’:[‘饺子R Us’],
“墨西哥”:墨西哥烤肉店
>>>菜肴=[“中国菜”、“泰国菜”]
>>>按菜系筛选(名称、菜系、菜系)
[‘皇后街咖啡馆’、‘饺子反斗城’]
"""
#对于我们想要的每种菜肴,检查价格范围内的名称是否属于该菜肴
结果=列表()
#对于菜系列表中的每个名称,我们检查餐厅名称是否在其中并将其返回
对于菜系列表中的菜肴:
对于名称中的名称匹配价格:
如果菜系中的名称为[菜系]且名称不在结果中:
result.append(名称)
返回结果
def read_餐厅(文件):
“(文件)->(dict,dict,dict)
根据文件中的信息返回三个字典的元组:
-{餐厅名称:评级%}的记录
-一份{价格:餐厅名称清单}的口述
-{cusine:餐厅名称列表}的一句话
"""
name_to_rating={}
价格到名称={'$':[],'$':[],'$$':[],'$$':[],'$$$':[]]
菜肴名称={}
打开(文件)为f时:
i=0
#将所有行(不带\n)存储到单词列表中的行
lines=f.read().splitlines()
而i
顺便说一下,原始文件不包含“%”符号。