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

标签 python generator enumerate

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

  • 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/

相关文章:

python - 使用 pybarcode ImageWriter 和 docx 模块将条形码图像附加到 docx 文件

python - 对numpy数组中的每个第n个条目进行二次采样

python - 允许用户从多个函数中进行选择以在 Python 中运行的最佳方式是什么?

c# - 数组在 foreach 循环中未正确初始化

python - 枚举的实现细节是什么?

python - 在 Python cffi 中的库之间传递对象

python - 链接 Python 生成器以遍历嵌套数据结构;最佳实践

python - 为什么将枚举函数结果传递给 dict 构造函数会产生类型警告?

c - 在输出数组编号的同时枚举C中的数组