2013-04-04 59 views
0

所以我是一名初學者程序員,並且學習編程:在cousera上製作高質量的代碼課程。我有一個文件restaurant_small.txt如何將項目從Python中的文件分配給字典?

restaurant.txt格式是餐廳的評價,

georgieporgie:50 
dumpling r us:70 
queens cafe:60 

我可以通過線上閱讀線

dictionary = {} 
our_file = open(file) 
#using an iterator to read files 
for line in iter(our_file): 
    dictionary = ?? 

我希望能夠建立一個字典{'restaurant':'rating'} 我該如何解決這個問題,一步一步讚賞

回答

2
dictionary = {} 
with open('restaurant_small.txt') as our_file: 
    for line in our_file: 
     rest, rating = line.split(':') 
     dictionary[rest] = int(rating) 

with statement是推薦的處理文件的方式,這些文件可以正確處理例外情況,並確保文件始終處於關閉狀態。這大致相當於

our_file = open('restaurant_small.txt') 
# do the rest 
our_file.close() 

只是如果事情close()前出了毛病,無論如何都會被調用。在with聲明的更緊密相當於將

our_file = open('restaurant_small.txt') 
try: 
    # do the rest 
finally: 
    our_file.close() 
+0

,如果你不介意的話,你能解釋線兩條 – 2013-04-04 12:37:28

+0

@SuziemacTani添加了解釋,並參考了很多感謝 – 2013-04-04 12:42:46

+0

,港島線接受的答案,我不能現在... – 2013-04-04 12:46:12

5

類似列弗的回答,而是先建立一個線發生器,從分裂結束,並使用字典理解建造起來一氣呵成......

with open('input') as fin: 
    lines = (line.rsplit(':', 1) for line in fin) 
    dictionary = {k:int(v) for k, v in lines} 
相關問題