我有一个文本文件,如下所示:
productName calories protein carb fat
我想在每一行中拆分单词,并使用这些变量创建一个对象。我写了这样的东西:
with open("Produkty.txt") as file:
for line in file:
(product, calories, protein, carb, fat) = line.split()
product = productBase(product, calories, protein, carb, fat)
问题是没有创建任何对象。 类本身看起来像这样:
class productBase:
def __init__(self, product, calories, protein, carb, fat):
self.product = product
self.calories = calories
self.protein = protein
self.carb = carb
self.fat = fat
我做了类似的事情,但是我的文件连续有2个单词,然后将它们写到了字典中。它是这样的:
with open("Produkty.txt") as file:
for line in file:
(product, calories) = line.split()
foodDictionary[product] = calories
我以为可以通过使用对象和类将更多信息添加到产品中,但是我无法使其正常工作。