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