guests = {}
def read_guestlist(file_name):
text_file = open(file_name,'r')
while True:
line_data = text_file.readline().strip().split(",")
yield line_data
if len(line_data) < 2:
# If no more lines, close file
text_file.close()
break
name = line_data[0]
age = int(line_data[1])
guests[name] = age
guestlist = read_guestlist('guest_list.txt')
for i in range(10):
next(guestlist)
guestlist.send('Jane,35')
这是Codacademy的做法。 给定的代码逐行读取文本文件,并用','分成两半,名字和年龄。 然后将它们放入空字典中。 有了生成器的概念,我想发送收益值。
但是,他们为我提供了一个字符串 'Jane,35' 并像我之前那样发送了值。
我的问题是字符串无法被“readline()”读取,正如我天真地做的“guestlist.send('Jane,35')',当我打印 geust 字典时,我看不到'Jane, 35' 我应该改变'yield line_data'的位置吗?或者我应该做什么? 提前谢谢你
您应该使用
with
语句逐行读取文件内容,然后拆分每一行并生成拆分文本,从而满足read_gueslist
函数内的几乎所有要求
例如:
def read_guestlist(file_name):
with open(filename) as text_file:
for line in text_file:
yield line.strip().split(',')
然后您可以使用函数的生成器功能来填充来宾词典。
for pair in read_guestlist(filename):
guests.update([pair])
所以它可能看起来像这样:
guests = {}
def read_guestlist(file_name):
with open(filename) as text_file:
for line in text_file:
yield line.strip().split(',')
for pair in read_guestlist(filename):
guests.update([pair])
这假设文件中的每一行都有两个值,用一个逗号分隔。如果不是这种情况,那么您可能需要进行一些错误检查。