从文本文件创建字典,其中包含一个键和一个由多个属性组成的集

2024-06-16 08:35:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

是否有一种不同的方法,可以将每一组属性手动复制到一个集合中并指定正确的键

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

Tags: 方法名称数量字典属性链接de手动
2条回答
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}

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

  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))

相关问题 更多 >