我试图遍历一个文本文件(包含多个故事)并返回一个列表列表,其中每个列表都是一个新的故事。
read_lines_in_text(fname)是一个生成器,我想对其进行迭代以读取文本文件中的每一行。这必须是一个生成器。
find_title(fname)是必须使用的函数,它返回出现标题的文本行的列表(并因此标志着新故事的开始)。
我在下面编写的代码可以完成这项工作,但是我认为这不是一个很好的解决方案。
newdict = {}
story = []
list_of_stories = []
for idx, line in enumerate(read_lines_in_text(fname)):
if line in find_title(fname):
newdict[idx] = line
for idx, line in enumerate(read_lines_in_text(fname)):
if idx >= list(newdict.keys())[0]:
if idx in newdict:
list_of_stories.append(story)
story = []
story.append(line)
else:
story.append(line)
鉴于我拥有每个标题在文本中出现的位置的索引,我想要具有以下内容:
for lines between key i and key i+1 in mydict:
append to story
list_of_stories.append(story)
story = []
答案 0 :(得分:3)
您根本不需要使用索引。只要有新标题,就开始新的story
列表,然后将前一个附加到list_of_stories
:
story = []
list_of_stories = []
titles = set(find_title(fname))
for line in read_lines_in_text(fname):
if line in titles:
# start a new story, append the previous
if story:
list_of_stories.append(story)
story = [line]
elif story: # a story has been started
story.append(line)
# handle the last story
if story:
list_of_stories.append(story)
使用生成器函数时,您真的想避免将其视为具有索引号的随机访问序列。
请注意,我们也避免为了获得标题而多次阅读fname
; titles
变量是find_title()
返回的一组标题字符串,存储为一组用于快速成员资格测试。