Я работаю над этим несколько дней, и я не могу заставить его работать. Я пытаюсь прочитать файл и аккумулировать некоторую информацию в три разных словаря. Это назначение для архивного онлайн-класса, и решение этого не было опубликовано.Чтение файла и аккумулирование информации в словаре в Python 3
Вот файл для чтения: Он начинается ниже.
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.
Оригинальный файл, кстати, не содержит знаков «%». –