Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在生成器上使用枚举分析文本_Python_Generator_Enumerate - Fatal编程技术网

Python 在生成器上使用枚举分析文本

Python 在生成器上使用枚举分析文本,python,generator,enumerate,Python,Generator,Enumerate,我试图迭代一个文本文件(包含几个故事)并返回一个列表,其中每个列表都是一个新故事 read_lines_in_text(fname)是一个生成器,我想迭代它来读取文本文件中的每一行。这必须是一个发电机 find_title(fname)是一个必须使用的函数,它返回文本中出现标题的行列表(因此表示新故事的开始) 我在下面编写的代码可以完成这项工作,但我认为这不是一个很好的解决方案 newdict = {} story = [] list_of_stories = [] for idx, li

我试图迭代一个文本文件(包含几个故事)并返回一个列表,其中每个列表都是一个新故事

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

您根本不需要使用索引。只要在有新标题时开始一个新的
故事
列表,然后将上一个附加到
故事列表

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()
返回的一组标题字符串,存储为一个集合,用于快速成员资格测试。

注意:您的
列表(newdict.keys())[0]
测试仅在Python 3.6或更新版本中有效,其中字典恰好按插入顺序列出键。任何早期的Python版本都可能给您错误的索引值。