【问题标题】:create a dictionary from a text file, which contains a key and a set made from multiple properties从文本文件创建一个字典,其中包含一个键和一个由多个属性组成的集合
【发布时间】:2019-01-23 22:50:51
【问题描述】:

文本文件包含奶酪的名称及其属性。每种奶酪的属性数量都不相同。 最终结果是一个字典,其中每个奶酪的名称是一个键,其属性是链接到该键的集合。

除了手动将每组属性复制到一个集合中并分配正确的键之外,还有其他方法吗?

champignon de luxe garlic,soft,soft-ripened,garlicky,herbaceous,herbal,spicy,cream,creamy,natural
bleu dauvergne,semi-soft,artisan,buttery,creamy,grassy,herbaceous,salty,spicy,tangy,strong,ivory,creamy and smooth,bloomy

【问题讨论】:

标签: python dictionary


【解决方案1】:
import csv

with open(filename) as cheeses:
    cheese_rows = csv.reader(cheeses)
    d = {cheese_row[0]: set(cheese_row[1:]) for cheese_row in cheese_rows}

这将创建一个字典,其中包含文件中每一行中第一个值的键,以及该行中一组其余值的值。

【讨论】:

    【解决方案2】:
    1. 逐行阅读文本。
    2. 用逗号分割字段(或使用csv 模块)
    3. 将它们添加到字典中

    给出代码:

    #! /usr/bin/env python3
    
    import sys
    
    # Empty dictionary to hold Cheese properties
    CHEESE = {}  
    
    try:
        fin = open("cheese.txt")
    except:
        sys.stderr.write("Failed to open input file\n")
        sys.exit(1)
    
    # EDIT: more comprehensive error catching
    line_count = 0
    try:
        for cheese_data in fin: # or  fin.readlines():
            line_count += 1
            # We're expecting name,property1,property2, ... ,propertyN
            fields = cheese_data.strip().split(',')
            if ( len( fields ) > 1 ):
                cheese_name = fields[0].capitalize()
                cheese_properties = fields[1:]
                # Add item to dictionary
                CHEESE[cheese_name] = cheese_properties
    except:
        sys.stderr.write("Error around line %u\n" % (line_count))
    finally:
        fin.close()
    
    ### ... do stuff with CHEESE dict
    
    print(str(CHEESE))
    

    【讨论】:

    • 有很多不相关的代码,例如文件不存在时的错误处理,检查是否len(fields) > 1,将奶酪名称大写,这完全是一种分心和不必要的。数据是一个不起眼的词,它都是数据。 readlines 效率低下,文件处理在异常情况下不会关闭,是单向的,print 会将CHEESE 转换为字符串,无需调用str 等。
    • 我同意彼得的观点。我认为您提供的步骤很棒,但代码过于冗长。
    • @PeterWood - “不相关的代码”是对 OP 的一种推动,他们在编写自己的代码时应该考虑这些事情。我假设,因为他们请求帮助进行如此简单的操作,所以他们是编程的初学者,需要进行输入数据完整性和错误检查等方面的工作。
    • 为什么向初学者发布非惯用的python?他们当然应该得到更好的,而不是更糟的?
    • 因为在这种情况下,非惯用代码更具可读性和可理解性。每个步骤都是一个单独的操作,可以单独拆分和吸收。简洁、惯用的答案非常适合软件工程师,但不适合绝对的初学者。
    猜你喜欢
    • 2023-01-11
    • 2019-10-05
    • 2015-11-15
    • 2017-05-01
    • 2016-03-08
    • 1970-01-01
    • 2019-06-15
    • 2020-05-02
    • 2012-03-09
    相关资源
    最近更新 更多