该文本文件包含奶酪的名称及其属性。每种奶酪的特性数量都不相同。 最终结果是一个字典,其中每个奶酪的名称是一个键,其属性是链接到该键的集合。
除了将每组属性手动复制到一组并分配正确的密钥之外,还有其他方法吗?
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
答案 0 :(得分: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}
这将创建一个字典,其中包含文件中每行中第一个值的键以及该行中其余值的集合的键。
答案 1 :(得分:0)
csv
模块)提供代码:
#! /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))