我的挣扎:
阅读两行,跳过第三行.
然后,我想将所有对象存储在以名称为键的字典中.
**** Ingredients.txt ****
Name1
ingredient1/ingredient2/ingredient3
Name2
ingredient1/ingredient2
Name3
...
class Foodset(object):
def __init__(self, name):
self.name = name
self.ingredients = set([])
def __str__(self):
return str(self.name) + ' consits of: ' + ", ".join(str(e) for e in self.ingredients) + '.'
def setIngredients(self, list):
for i in list:
self.ingredients.add(i)
def getMenu(file="ingredients.txt"):
with open(file, 'r') as indata:
menu = dict()
for line in indata:
tempString = str(line.rstrip('\n'))
menu[tempString] = Foodset(tempString)
我想阅读下一行并将其存储为配料,然后跳过第三行,因为它是空白.然后重复.
我在for循环中遇到的问题是,我无法在同一循环中存储两条不同的线,然后再引用同一对象才能使用setIngredients()方法.我还可以通过哪些其他方式读取每个循环中的多行内容?
编辑:
@Arpan提供了一个快速解决方案,可以使用indata.readlines()列出每行并以3的步长循环,同时存储第一个和第二个值,并跳过第三个值.
我刚刚在while循环中使用了readline()方法3次,提出了另一个解决方案.使用readline()是我最初想要的.
def getMenu(menu="ingredients.txt"):
with open(menu, "r") as indata:
menu = dict()
while True:
name = indata.readline().strip('\n')
ingredientList = indata.readline().strip().split('/')
if name == "":
break
# here I just added a parameter that directly set the attribute "ingredients" inside the object.
menu[name] = Foodset(name, ingredientList)
indata.readline()
return menu
解决方法:
尝试这样的事情.
with open(file, 'r') as indata:
lines = indata.readlines()
menu = dict()
for i in xrange(0, len(lines), 3):
name = lines[i].rstrip('\n')
ingredients = lines[i+1].rstrip('\n').split('/')
f = Foodset(name)
f.setIngredients(ingredients)
menu[name] = f
对于python 3.x,请使用range而不是xrange.