在Python 3中读取文件并将信息累积到字典中

问题描述 投票:0回答:2

我已经在这个工作了几天,我无法让它工作。我正在尝试读取文件并将一些信息累积到三个不同的字典中。这是归档在线课程的作业,并未发布解决方案。

这是要读取的文件:它从下面开始。

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。

dictionary
2个回答
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()

0
投票

我认为上面的答案没有正确保存cuisine_by_names字典。见下面的代码。这有效:

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
© www.soinside.com 2019 - 2024. All rights reserved.