Skip to main content
 首页 » 编程设计

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

2025年05月04日17rubylouvre

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

一个例子是最好的:

    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 看起来有点勉强。

谢谢,

将

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

请您参考如下方法:

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

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.'] 

(如果你真的想创建一个列表,区别不大。这主要取决于你有多少句子以及你想用“上下文”做什么)/p>

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