iterator - 使用 python 连接上一句和下一句

标签 iterator python

我正在尝试连接列表中包含的一组句子。我有一个函数可以确定一个句子是否值得保存。然而,为了保留句子的上下文,我还需要保留它之前和之后的句子。在边缘情况下,无论是第一个句子还是最后一个句子,我都会保留该句子及其唯一的邻居。

最好举个例子:

    ex_paragraph = ['The quick brown fox jumps over the fence.', 
                   'Where there is another red fox.', 
                   'They run off together.', 
                   'They live hapily ever after.']
    t1 = lambda x: x.startswith('Where')
    t2 = lambda x: x'startswith('The ')

t1 的结果应该是:

['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.']

t2 的结果应该是:

['The quick brown fox jumps over the fence. Where there is another red fox.']

我的解决方案是:

def YieldContext(sent_list, cont_fun):
    def JoinSent(sent_list, ind):
        if ind == 0:
            return sent_list[ind]+sent_list[ind+1]
        elif ind == len(sent_list)-1:
            return sent_list[ind-1]+sent_list[ind]
        else:

            return ' '.join(sent_list[ind-1:ind+1])


    for sent, sentnum in izip(sent_list, count(0)):
        if cont_fun(sent):
            yield JoinSent(sent_list, sent_num)

有谁知道一种“更干净”或更Pythonic的方式来做这样的事情。 if-elif-else 似乎有点牵强。

谢谢

PS。显然我是用一个更复杂的“上下文函数”来做这件事,但这只是一个简单的例子。

最佳答案

在列表的开头和结尾附加一个空字符串实际上是一个好主意,但实际上没有必要使用花哨的列表理解等。您可以非常轻松地构建生成器:

def yieldContext(l, func):
    l = [''] + l + ['']
    for i, s in enumerate(l):
        if func(s):
            yield ' '.join(l[i-1:i+2]).strip()

给出:

>>> print list(yieldContext(ex_paragraph, t1))
['The quick brown fox jumps over the fence. Where there is another red fox. They run off together.']

>>> print list(yieldContext(ex_paragraph, t2))
['The quick brown fox jumps over the fence. Where there is another red fox.']

(如果您确实想创建一个列表,则没有太大区别。这主要取决于您有多少个句子以及您想对“上下文”执行什么操作)

def yieldContext(l, func):
    l = [''] + l + ['']
    return [' '.join(l[i-1:i+2]).strip() for i, s in enumerate(l) if func(s)]

关于iterator - 使用 python 连接上一句和下一句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3070695/

相关文章:

scala - 迭代器上的Scala映射不会产生副作用

java - 第二次调用带有迭代器的方法会抛出 ConcurrentModificationException

java - 使用迭代器的 nosuchElementException 问题

Ruby:隐式 block 迭代器

python - 从 git bash for windows 激活 venv

python - Pandas 蟒 : Writing output to specific cells in the CSV

python - Groupby 使用列和索引,然后求和以创建新列

c++ - 何时返回 vector 迭代器而不是 vector ?

python - 从字典中获取特定键的方法

python - 使用 Python 进行傅里叶变换