gpt4 book ai didi

python - 在生成器上使用枚举来解析文本

转载 作者:行者123 更新时间:2023-11-30 22:05:25 25 4
gpt4 key购买 nike

我正在尝试迭代一个文本文件(包含多个故事)并返回一个列表列表,其中每个列表都是一个新故事。

  • 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 = []

最佳答案

您根本不需要使用索引。只要每当您有了新标题就开始一个新的故事列表,并将前一个添加到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)

使用生成器函数时,您确实希望避免将其视为带有索引号的随机访问序列。

请注意,我们还避免仅仅为了获取标题而多次读取 fnametitles 变量是由 find_title() 返回的一组标题字符串,存储为一组以进行快速成员资格测试。

关于python - 在生成器上使用枚举来解析文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53021742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com