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)
누구나 이와 같은 작업을하는 "더 깨끗한"방법이나 더 평범한 방법을 알고 있습니까? if-elif-else
은 약간 강제 된 것처럼 보입니다.
감사합니다,
윌
PS. 분명히 더 복잡한 "문맥 함수"를 사용하여 이것을 수행하고 있습니다. 그러나 이것은 간단한 예제 일뿐입니다.
from itertools import izip, tee
prev, this, next = tee([''] + ex_paragraph + [''], 3)
this.next()
next.next()
next.next()
[' '.join(ctx).strip() for ctx in izip(prev, this, next) if cont_fun(this)]
cont_fun
이 t1
또는 t2
중 하나입니다
내가 생각 하기엔, 비록 내가 Judo라는 인상을 받았지만, 발전기를 사용하여리스트를 만들려고했다. ... –
@David Zaslavsky : 글쎄, 그것은 그가 가지고있는 데이터에 달려있다. 그리고 어쨌든 차이가별로 없습니다 ... –
멋지고 읽을 수있는 ... 정확히 내가 무엇을 찾고 있었습니까! – JudoWill