从 .txt 文件打印请求的数据

Print requested data from .txt file

我有一个包含以下数据的 txt 文件:

buy apples 20
buy oranges 15
sold bananas 5
sold bananas 5
sold pears 8

我写了一个程序来打印香蕉的总售出数量,但是我总是报错

cannot unpack non-iterable builtin_function_or_method object

我该如何解决这个问题?

with open("update.txt") as openfile:
        for line in openfile:
            action, fruit, quantity = line.split
            if action == 'sold':
                    print(f"{fruit} {quantity}")

输出应该是:

bananas 10
pear    8

首先,您需要将 split 作为函数调用,即带括号:

action, fruit, quantity = line.split()

另外,如果你想总结每个水果的价值,你显然不能边读边打印。一种方法是例如将每个售出的水果存储在 dict 中并汇总数量。然后在最后打印它们:

# initialize empty dictionary
sold_fruit = {}

with open("update.txt") as openfile:
    for line in openfile:
        action, fruit, quantity = line.split()
        if action == 'sold':
            # set value for key '<fruit>' to the sum of the old value (or zero if there is no value yet) plus the current quantity
            sold_fruit[fruit] = sold_fruit.get(fruit,0) + int(quantity)

for frt, qty in sold_fruit.items():
    print(f"{frt} {qty}")

输出:

bananas 10
pears 8