【问题标题】:Populate dictionaries from text file从文本文件填充字典
【发布时间】:2013-03-15 19:23:49
【问题描述】:

我有一个文本文件,其中包含一系列餐厅的详细信息。详细信息是特定餐厅的名称、评级、价格和菜肴类型。文本文件的内容如下。

George Porgie
87%
$$$
Canadian, Pub Food

Queen St. Cafe
82%
$
Malaysian, Thai

Dumpling R Us
71%
$
Chinese

Mexican Grill
85%
$$
Mexican

Deep Fried Everything
52%
$
Pub Food

我想创建一组字典,如下所示:

Restaurant name to rating:
# dict of {str : int}
name_to_rating = {'George Porgie' : 87,
'Queen St. Cafe' : 82,
'Dumpling R Us' : 71,
'Mexican Grill' : 85,
'Deep Fried Everything' : 52}

Price to list of restaurant names:
# dict of {str : list of str }
price_to_names = {'$'   :  ['Queen St. Cafe', 'Dumpling R Us', 'Deep Fried Everything'],
'$$'  :  ['Mexican Grill'],
'$$$' :  ['George Porgie'], 
'$$$$' : [ ]}

Cuisine to list of restaurant name:
#dic of {str : list of str }
cuisine_to_names = {'Canadian' : ['George Porgie'],
'Pub Food' : ['George Porgie', 'Deep Fried Everything'],
'Malaysian' : ['Queen St. Cafe'],
'Thai' : ['Queen St. Cafe'],
'Chinese' : ['Dumpling R Us'],
'Mexican' : ['Mexican Grill']}

在 Python 中填充上述字典的最佳方法是什么?

【问题讨论】:

  • 向我们展示您的尝试。
  • 我只知道使用 Python 从文本文件中逐行读取
  • 这是 Coursera 的作业。
  • @Bibhas。这个例子确实来自coursera。但这不是在课程中包含任何学分的家庭作业。如果这是一个值得称赞的练习,我就不会在这里问它。如果您不能提供任何有建设性的内容,请不要发表评论。
  • 这是在早期课程中非常显着地出现的东西 - 您仍然可以审核。如果您可以访问该课程并阅读这些内容,它将大量提供帮助。我意识到教科书也没有这个,但在这种情况下帮助自己可能会更好。看看学习编程第 6 周和第 7 周

标签: python file io dictionary


【解决方案1】:

初始化一些容器:

name_to_rating = {}
price_to_names = collections.defaultdict(list)
cuisine_to_names = collections.defaultdict(list)

将您的文件读入临时字符串:

with open('/path/to/your/file.txt') as f:
  spam = f.read().strip()

假设结构是一致的(即由双换行符分隔的 4 行块),遍历这些块并填充您的容器:

restraunts = [chunk.split('\n') for chunk in spam.split('\n\n')]
for name, rating, price, cuisines in restraunts:
  name_to_rating[name] = rating
  # etc ..

【讨论】:

    【解决方案2】:

    对于主要的阅读循环,您可以使用枚举和取模来知道一行上的数据是什么:

    for lineNb, line in enumerate(data.splitlines()):
        print lineNb, lineNb%4, line
    

    对于price_to_namescuisine_to_names 字典,您可以使用默认字典:

    from collections import defaultdict
    price_to_names = defaultdict(list)
    

    【讨论】:

    • @niroyb:我正在研究你的答案。太感谢了。会回来的。
    猜你喜欢
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多