2015-06-09 2 views
0

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

+0

Оригинальный файл, кстати, не содержит знаков «%». –

ответ

0

Файл, который вы пытаетесь прочитать, является окончательным результатом, а не оригиналом. Ниже приведено одно решение с исходными данными в 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() 
Смежные вопросы