在生成器上使用枚举来解析文本
Using enumerate on a generator to parse text
我正在尝试迭代一个文本文件(包含多个故事)和 return 列表列表,其中每个列表都是一个新故事。
read_lines_in_text(fname) 是一个生成器,我想遍历它以读取文本文件中的每一行。这必须保留为生成器。
find_title(fname) 是必须使用的函数,returns 是文本中出现标题的行的列表(因此表示开始一个新的故事)。
我在下面编写的代码可以完成这项工作,但我认为这不是一个很好的解决方案。
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 = []
您根本不需要使用索引。只要有新标题就开始一个新的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()
返回的标题字符串,存储为一组用于快速成员资格测试。
我正在尝试迭代一个文本文件(包含多个故事)和 return 列表列表,其中每个列表都是一个新故事。
read_lines_in_text(fname) 是一个生成器,我想遍历它以读取文本文件中的每一行。这必须保留为生成器。
find_title(fname) 是必须使用的函数,returns 是文本中出现标题的行的列表(因此表示开始一个新的故事)。
我在下面编写的代码可以完成这项工作,但我认为这不是一个很好的解决方案。
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 = []
您根本不需要使用索引。只要有新标题就开始一个新的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()
返回的标题字符串,存储为一组用于快速成员资格测试。