2013-04-04 113 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} 
相关问题