2017-04-03 64 views
1

我對Python相當陌生,但是我沒有找到對這個特定問題的答案。 我正在寫一個簡單的推薦程序,我需要一本字典,其中美食是關鍵,餐廳的名字是一種價值。有幾個例子,我必須分割一些菜名,並確保所有其他餐廳(價值)具有相同的美食分配給相同的菜(關鍵)。這裏有一個文件的一部分:將多個值分配給Python中的文件的字典鍵3

Georgie Porgie 
87% 
$$$ 
Canadian, Pub Food 

Queen St. Cafe 
82% 
$ 
Malaysian, Thai 

Mexican Grill 
85% 
$$ 
Mexican 

Deep Fried Everything 
52% 
$ 
Pub Food 

所以它只是第一個和最後一個使用相同的美食,但越到後來的文件中也有。 這裏是我的代碼:

def new(file): 
    file = "/.../Restaurants.txt" 
    d = {} 
    key = [] 
    with open(file) as file: 
     lines = file.readlines() 

    for i in range(len(lines)): 
     if i % 5 == 0: 
      if "," not in lines[i + 3]: 
       d[lines[i + 3].strip()] = [lines[i].strip()] 
      else: 
       key += (lines[i + 3].strip().split(', ')) 
       for j in key: 
        if j not in d: 
         d[j] = [lines[i].strip()] 
        else: 
         d[j].append(lines[i].strip()) 
    return d 

它讓所有的按鍵和打印的值,但它並沒有在它應該分配兩個值相同的密鑰。另外,在最後的'else'聲明中,第二個餐館被分配了錯誤的鑰匙作爲第二個值。這不應該發生。我會很感激任何意見或幫助。

回答

1

在只有一個類別的情況下,您不檢查密鑰是否在字典中。你應該像在多個類別的情況下那樣做,然後工作正常。

我不知道爲什麼你有文件作爲參數,當你有一個文件,然後覆蓋。

另外,你應該做的「鑰匙」對於每個結果,而不是+ =(將它添加到現有的「關鍵」

當你檢查是否j是字典,清潔方法是檢查是否j是鍵(運行起來也())

def new(file): 
    file = "/.../Restaurants.txt" 
    d = {} 
    key = [] 
    with open(file) as file: 
     lines = file.readlines() 

    for i in range(len(lines)): 
     if i % 5 == 0: 
      if "," not in lines[i + 3]: 
       if lines[i + 3] not in d.keys(): 
        d[lines[i + 3].strip()] = [lines[i].strip()] 
       else: 
        d[lines[i + 3]].append(lines[i].strip()) 

      else: 
       key = (lines[i + 3].strip().split(', ')) 
       for j in key: 
        if j not in d.keys(): 
         d[j] = [lines[i].strip()] 
        else: 
         d[j].append(lines[i].strip()) 
    return d 
0

通常情況下,我發現,如果你使用的名稱爲字典鍵,你可以有一個更簡單的時間後,處理它們。

在下面的例子中,我返回一系列字典,每個餐廳都有一個字典,還包含proc的功能在一個名爲add_value()的方法中使用值,以使代碼更具可讀性。

在我的例子中,我使用編解碼器來解碼值。雖然不是必要的,但取決於你處理的字符,這可能是有用的。我也使用itertools來用迭代器讀取文件行。再次,根據情況不需要,但如果您處理真正的大文件可能會有用。

import copy, itertools, codecs 

class RestaurantListParser(object): 

    file_name = "restaurants.txt" 

    base_item = { 
     "_type": "undefined", 
     "_fields": { 
      "name": "undefined", 
      "nationality": "undefined", 
      "rating": "undefined", 
      "pricing": "undefined", 
     } 
    } 


    def add_value(self, formatted_item, field_name, field_value): 

     if isinstance(field_value, basestring): 
      # handle encoding, strip, process the values as you need. 
      field_value = codecs.encode(field_value, 'utf-8').strip() 
      formatted_item["_fields"][field_name] = field_value 
     else: 
      print 'Error parsing field "%s", with value: %s' % (field_name, field_value) 


    def generator(self, file_name): 

     with open(file_name) as file: 

      while True: 
       lines = tuple(itertools.islice(file, 5)) 
       if not lines: break 


       # Initialize our dictionary for this item 
       formatted_item = copy.deepcopy(self.base_item) 

       if "," not in lines[3]: 
        formatted_item['_type'] = lines[3].strip() 
       else: 
        formatted_item['_type'] = lines[3].split(',')[1].strip() 
        self.add_value(formatted_item, 'nationality', lines[3].split(',')[0]) 

       self.add_value(formatted_item, 'name', lines[0]) 
       self.add_value(formatted_item, 'rating', lines[1]) 
       self.add_value(formatted_item, 'pricing', lines[2]) 

       yield formatted_item 

    def split_by_type(self): 

     d = {} 
     for restaurant in self.generator(self.file_name): 
      if restaurant['_type'] not in d: 
       d[restaurant['_type']] = [restaurant['_fields']] 
      else: 
       d[restaurant['_type']] += [restaurant['_fields']] 

     return d 

然後,如果你運行:

p = RestaurantListParser() 
print p.split_by_type() 

你應該得到:

{ 
    'Mexican': [{ 
     'name': 'Mexican Grill', 
     'nationality': 'undefined', 
     'pricing': '$$', 
     'rating': '85%' 
    }], 
    'Pub Food': [{ 
     'name': 'Georgie Porgie', 
     'nationality': 'Canadian', 
     'pricing': '$$$', 
     'rating': '87%' 
    }, { 
     'name': 'Deep Fried Everything', 
     'nationality': 'undefined', 
     'pricing': '$', 
     'rating': '52%' 
    }], 
    'Thai': [{ 
     'name': 'Queen St. Cafe', 
     'nationality': 'Malaysian', 
     'pricing': '$', 
     'rating': '82%' 
    }] 
} 

你的辦法很簡單,所以沒關係。當我想到這類問題時,我想提一些想到的想法。

相關問題