我打开一个包含以下内容的文件:
TransactionNo Date CustomerId PurchasePairs
------------- ---- ---------- -------------
1 09-04-2014 barakobama potatoes:2.67,sugar:1.98,cereal:5.99,crisps:1.09
2 11-04-2014 barakobama parsley:0.76,cereal:3.22
3 11-04-2014 vladimirputin bread:0.66,milk:2.87,parsley:1.33
我想要这样的输出字典:
{'milk': {'vladimirputin': 2.87}, 'cereal': {'barakobama': 9.21},
'bread': {'vladimirputin': 0.66}, 'potatoes': {'barakobama': 2.67},
'sugar': {'barakobama': 1.98}, 'parsley': {'vladimirputin': 1.33,
我已经做到了:
C={}
file=open(fileNameStr,'r')
for line in file:
if line[0].isdigit():
fields = line.split()
c = {}
f = open(fileNameStr)
for line in f:
if not line[0].isdigit(): continue
transactionNo, _date, customerId, purchasePairs = line.split()
for pair in purchasePairs.split(','):
productName, price = pair.split(':')
if productName in c:
c[productName][customerId] = float(price)
else:
c[productName] = {customerId: float(price)}
你必须处理一种情况:顾客购买同一件东西不止一次。希望这段代码能有所帮助。
#!/usr/bin/python3
final_products = dict()
file_name = "myfile"
try:
# it's better not to use reserved name like 'file'
# fhd, for example, is better
# you might want to remove encoding='utf-8' depending on your python version (2 or 3) :
fhd = open(file_name, 'rt', encoding='utf-8')
except:
# here we cannot read the file
raise
else:
# ok, file is opened
for line in fhd:
if line[0].isdigit():
fields = line.split()
# there should be exactly 4 fields
if len(fields) == 4:
products = fields[3].split(',')
consumer = fields[2]
for p in products:
product_details = p.split(':')
if len(product_details) == 2:
product_name = product_details[0]
product_quantity = float(product_details[1])
# first we check if the product is in the dict
# if not we add it
if product_name not in final_products.keys():
final_products[product_name] = dict()
# does the consumer already bought this product ?
if consumer not in final_products[product_name].keys():
final_products[product_name][consumer] = 0.0
# finaly we add the quantity bought by the consumer
final_products[product_name][consumer] += product_quantity
# close the file
fhd.close
print(final_products)
此打印:
{'cereal': {'barakobama': 9.21}, 'potatoes': {'barakobama': 2.67}, 'parsley': {'vladimirputin': 1.33, 'barakobama': 0.76}, 'sugar': {'barakobama': 1.98}, 'crisps': {'barakobama': 1.09}, 'milk': {'vladimirputin': 2.87}, 'bread': {'vladimirputin': 0.66}}