问题描述
然后我想将所有对象存储在名称为键的字典中.
Then I want to store all the objects in a dictionary with the name as keys.
**** 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)
我想阅读下一行并将其存储为配料,然后跳过第三行,因为它是空白.然后重复.
I want to read the next line and store as ingredients and then skip the third line since it's blank. Then repeat.
for循环遇到的问题是,我不能在同一循环中存储两条不同的线,然后再引用同一对象才能使用setIngredients()方法.我还可以通过哪些其他方式读取每个循环中的多行内容?
The problem I'm having with the for loop is that I can't store two different lines in the same loop and then refer to the same object in order to use the setIngredients() method. What other ways can I read multiple lines inside each loop?
@Arpan提出了一种快速解决方案,可以使用indata.readlines()列出每行并以3的步长循环,同时存储第一个和第二个值,并跳过第三个值.
@Arpan came up with a quick solution to use indata.readlines() to make a list of every line and loop with steps of 3 while storing first and second value and skipping the third.
我刚刚在while循环内使用 readline()方法3次提出了另一种解决方案.我本来想要使用readline().
I just came up with an other solution using the readline() method 3 times inside a while loop. Using readline() is what I originally wanted.
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
.
For python 3.x use range
instead of xrange
.
这篇关于Python:从文件中读取多行并将实例存储在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!